【问题标题】:How to use $geoNear on array of embedded documents?如何在嵌入式文档数组上使用 $geoNear?
【发布时间】:2015-12-03 03:10:25
【问题描述】:

我的文档结构如下:

{ agency_key : '',
  route_id: '',
  direction_id: '',
  stops: [ 
           {stop_id:15, 
            stop_lat: '',
            stop_lon: '',
            loc: [-83.118972, 42, 121567]
            },
            {...
            }
          ]
}

我想在集合中的每个文档的给定距离内找到靠近给定 (lat,lon) 对的停靠点。我创建了二维索引。我试过 $unwind,然后 $geoNear 但它说 $geoNear 只能在管道的第一阶段。 我试过这个:

db.tm_stops.aggregate([ 
... { 
...  $geoNear: { near: {coordinates: [-82.958841, 42.370114] },      distanceField: "stops.calculated", query: { agency_key: "DDOT"}, 
... includeLocs: "stops.loc" }
... }
... ])

我尝试了以下方法:

 db.tm_stops.find({stops:{$near:[-82.958841, 42.370114], $maxDistance: 1 } } )

它会抛出这个错误:

error: {
    "$err" : "Unable to execute query: error processing query: ns=gtfs.tm_stops limit=0 skip=0\nTree: GEONEAR  field=stops maxdist=1 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query",
    "code" : 17007

我的 mongo 查询应该是什么?我需要从 Node.js 应用程序执行此操作,但我想先在 Mongo shell 中查看一些结果。提前致谢。

【问题讨论】:

    标签: node.js mongodb aggregation-framework pipeline


    【解决方案1】:

    我终于完成了查询。我正在回答我自己的问题以供将来参考。 由于我使用的是 2d 索引而不是 2dsphere,因此我不必在 near 运算符中使用 coordinates。此查询有效:

    db.tm_stops.aggregate([ 
     { 
      $geoNear: 
        { near: [-82.958841, 42.370114] ,     
         distanceField: "stops.calculated", 
         query: { agency_key: "DDOT"}, 
         includeLocs: "stops.loc" }
         }
       ])
    

    但我发现,在返回的文档中,我只能看到计算出的距离和用于计算距离的 (lon, lat) 对。我不能真正返回用于计算的整个嵌入文档。

    如果我找到返回整个嵌入文档的方法,我会更新我的答案。

    【讨论】:

    • 在文档中添加 key 是不够的。还添加includeLocs 有助于...
    猜你喜欢
    • 2020-10-02
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多