-1

我目前正在使用带有 node.js 和 Mongoose 的 MongoDB 来执行地理空间搜索。

我正在使用以下文档和集合:

  • 航路点是包含位置和其他元数据的文档(就在那里,与此问题无关)
  • 目标集合包含1...n 航点
  • 来源集合包含确切的1 航点

这些文档可能看起来像什么的简单示例:

// Target
{
  waypoints: [
    {
      loc: [61.24, 22.24],
      time: 0
    },
    {
      loc: [61.25, 22.24],
      time: 1
    },
    {
      loc: [61.26, 22.24],
      time: 2
    },
  ]
}

// Source
{
  waypoint: {
    loc: [61.24, 22.24],
    time: 0
  }
}

所以我的问题是:

鉴于我们有一个特定的target文档(如上面的文档),找到source靠近(在 MAX_DISTANCE 的距离内)任何给定航路点的所有文档的最简单方法是target什么?

单个航路点的匹配是微不足道的:

Source.find({
  'from.loc': {
    $within: {
      $center: [target.waypoints[0].loc, MAX_DISTANCE],
      $uniqueDocs: true
    }
  }
})

但是,我正在努力寻找如何匹配任何给定航点的解决方案。例如以下查询不起作用:

Source.find({
  $or: [
    {
      'waypoint.loc': {
        $within: {
          $center: [target.waypoints[0].loc, MAX_DISTANCE],
          $uniqueDocs: true
        }
      }
    },
    {
      'waypoint.loc': {
        $within: {
          $center: [target.waypoints[1].loc, MAX_DISTANCE],
          $uniqueDocs: true
        }
      }
    },
    {
      'waypoint.loc': {
        $within: {
          $center: [target.waypoints[2].loc, MAX_DISTANCE],
          $uniqueDocs: true
        }
      }
    }
  ] 
})

有什么想法为什么这不起作用,还有什么替代方法?

非常感谢所有帮助!

PS 我正在使用 MongoDB v2.0.5、Mongoose 2.7.4 和节点 v0.8.7

4

1 回答 1

2

$or无论如何,查询在内部都是作为单独的查询实现的,所以除了缺乏优雅之外,像下面这样的工作没有太多的膨胀(在下划线库的帮助下):

var nearSources = {}, count = target.waypoints.length;
target.waypoints.forEach(function (waypoint) {
  Source.find({
    'waypoint.loc': {
      $within: {
        $center: [waypoint.loc, MAX_DISTANCE],
        $uniqueDocs: true
      }
    }
  }, function (err, sources) {
    if (sources) {
      // Add the unique sources to the nearSources object by _id.
      sources.forEach(function (source) {
        nearSources[source._id] = source;
      });
    }
    if (--count === 0) {
      // Done!  Convert nearSources to an array of source docs.
      nearSources = _.values(nearSources);
    }
  });
});
于 2012-08-23T01:00:10.140 回答