【问题标题】:Mongo query with $geoWithin and $near together将 $geoWithin 和 $near 放在一起的 Mongo 查询
【发布时间】:2018-08-24 05:09:20
【问题描述】:

我的用例是我想获取城市内的所有记录,并且应该首先获取附近的某个位置。 假设我有以下记录:

{"name" : "A", "location" : {"point" : [latlngs1]}}, //LatLng1 is in cityA
{"name" : "B", "location" : {"point" : [latlngs2]}}, //LatLng2 is in cityB
{"name" : "C", "location" : {"point" : [latlngs3]}}, //LatLng3 is in cityA
{"name" : "D", "location" : {"point" : [latlngs4]}}  //LatLng4 is in cityA

我希望获取 CityA 内所有附近 latlng5 的记录。

说距离bw位置点

[latlng5, latlng1] --> 10 unit
[latlng5, latlng3] --> 5 unit
[latlng5, latlng4] --> 8 unit

所以结果应该是这样的:

{"name" : "C"},
{"name" : "D"},
{"name" : "A"}

通过我的研究,我发现$geoWithin 最适合应用有界查询,因此我可以使用 $geoWithin 查找城市内的记录。

db.TEST.aggregate( [ { $match: {"location.point" : {$geoWithin: {$box: [[northEastLngLat],[SouthWestLngLat] ] } } }, {$project: {name: 1}}]).pretty();

这带来了记录:A、C 和 D 现在对于附近的地方,我首先发现$geoNear 适合这里。 所以查询就像:

b.TEST.aggregate([ {"$geoNear" : {near: [latlng5], distanceField: “距离”,球形:真}},{$match:{“location.point”: {$geoWithin: {$box: [[northEastLngLat],[SouthWestLngLat] ]}}}, {$project: {name: 1}}]).pretty();

但这不会产生任何输出。我尝试更改 $near 的 latlngs 有时在少数情况下会产生 1 个结果,而对于其他 0 个结果。

我的查询出了什么问题。请帮忙。 谢谢你

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你应该试试这个,它将获取 10 公里内的所有记录

     db.city.find({ 
       location :{
         $near : {
      $geometry : {   
         index : "Point" ,
         coordinates : [19.1, 72.89]
        },
     $maxDistance : 10000
    }
     }
         })
    

    它将返回所有记录并确保您在位置上有索引

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-03
      • 2016-07-24
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多