$geoNear、$near和$nearSphere在此上下文中不被允许。

3

我正在编写一个聚合查询,试图匹配某个区域内的用户。我遵循了 3.6 版本的文档(我的版本是 mongodb)。

db.collection('users').aggregate([
      {$match: {
        location: {
          $geoNear: {
            near: {type: 'Point', coordinates: [lng, lat]},
            maxDistance: globalConf.maxDistance * 1000
          }
        }
      }})

如果我在find上下文中使用此匹配项,它可以工作。如何修改查询才能在聚合上下文中运行?
我收到的错误是$geoNear、$near和$nearSphere在此上下文中不允许

4
$geoNear 是聚合管道阶段而非聚合操作符。因此请移除 $match 并将其用于顶层。 - undefined
users集合中,我应该把location字段放在哪里? - undefined
1
哪个location字段?地理空间索引将为您完成这项工作。 - undefined
1个回答

3

$geoNear 必须在聚合管道阶段中出现,并且由于我的 location 字段是 2dsphere 类型,我必须包含 {spherical: true}

因此,结果将会是:

 db.collection('users').aggregate([
    $geoNear: {
      includeLocs: "location",
      distanceField: "distance",
      near: {type: 'Point', coordinates: [lng, lat]},
      maxDistance: globalConf.maxDistance * 1000,
      spherical: true
    }
])

我不认为这样会起作用,因为你没有在聚合管道中添加阶段。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接