MongoDB $ nearSphere没有按预期工作

时间:2014-12-15 13:49:33

标签: mongodb

很难理解尝试返回距离给定点的某个距离(m)内的位置。

鉴于以下文件:

{
    "_id" : ObjectId("548edee849847b6cd7c78de9"),
    "name" : "A",
    "locations" : [ 
        {
            "name" : "place A",
            "position" : {
                "type" : "Point",
                "coordinates" : [ 
                    18.0244639, 
                    -18.0455594
                ]
            }
        }, 
        {
            "name" : "place B",
            "position" : {
                "type" : "Point",
                "coordinates" : [ 
                    28.0244639, 
                    -26.0455594
                ]
            }
        }, 
        {
            "name" : "place C",
            "position" : {
                "type" : "Point",
                "coordinates" : [ 
                    40.0244639, 
                    -40.0455594
                ]
            }
        }
    ]
}

我正在尝试仅返回上面名为地方b 的位置。我使用以下查询,但继续地点A 返回!

db.test.find(
   { "locations.position":{  $nearSphere: { //tried $near too
           $geometry: {
              type : "Point",
              coordinates : [ 28.0244639, -26.0455594 ]
           },
           $maxDistance: 100
        }
     }
   }, 
   {
       _id: 0, 'locations.$': 1
   }
)

1 个答案:

答案 0 :(得分:1)

使用$ near无法正确使用,但确实切换回$ geoWithin,根据@Asya显然要快得多:

db.test.find(
{
   "locations.position": {
      $geoWithin: { $center: [
          [ 28.0244639, -26.0455594], // longitude, latitude
            0.5/6371 // 500m radius 6371
          ] }
   }
},
    {"locations.$": 1} // projection 
)