【问题标题】:$geoNear, $near, and $nearSphere are not allowed in this context [duplicate]在此上下文中不允许使用 $geoNear、$near 和 $nearSphere [重复]
【发布时间】:2018-11-04 00:45:56
【问题描述】:

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

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

如果我在 find 上下文中使用此匹配项,它会起作用。如何修改查询以使其在聚合上下文中工作?

我得到的错误是$geoNear, $near, and $nearSphere are not allowed in this context

【问题讨论】:

  • $geoNear 是聚合管道阶段而不是聚合运算符。所以删除$match 并在顶层使用它。
  • 我应该将location 字段(users 集合中的那个)放在哪里?
  • 哪个location 字段? geospatial index 将为您完成这项工作。
  • 是的。非常感谢。

标签: mongodb aggregation-framework


【解决方案1】:

$geoNear 必须处于聚合管道阶段。我必须包含{spherical: true},因为我的location 字段是2dsphere 类型

所以,结果是

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

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 2017-11-03
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 2023-04-02
    相关资源
    最近更新 更多