2016-03-24 28 views
0

我在MongoDB中有如下記載:

{ 
    "_id" : ObjectId("56e63313059484f212a4305f"), 
    "title" : "The video title", 
    "location" : { 
     "coordinates" : [ 
      -73.9667, 
      40.78 
     ], 
     "type" : "Point" 
    }, 
} 

我希望能夠在那個確切位置找到的所有點。 如果我寫:

db.videos.find({ 
    location: { 
    '$nearSphere': { 
     '$geometry': { 
     type: 'Point', 
     coordinates: [-73.9667, 40.78] 
     }, 
     '$maxDistance': 0 
    } 
    } 
})[0] 

我沒有得到任何結果。如果我輸入:

db.videos.find({ 
    location: { 
    '$nearSphere': { 
     '$geometry': { 
     type: 'Point', 
     coordinates: [-73.9667, 40.78] 
     }, 
     '$maxDistance': 0.00001 
    } 
    } 
})[0] 

我得到了一個結果。

我看了又看,無處在文檔說maxDistance不能爲0

可以嗎?

回答

0

因此,作爲將使感,$maxDistance設置爲0會就像如果你沒有設置選項被忽略。

如果你正在尋找一個「完全匹配」,那麼只是要求。這不是一個$nearSphere查詢任何描述:

db.videos.find({ 
    "location.coordinates" : [ -73.9667, 40.78 ] 
}) 

這當然會返回文檔匹配的是「精確」的位置。

對於更復雜一點的東西,請改用聚合$geoNear。其將一個「距離」,你可以在後面的過濾使用:

db.videos.aggregate([ 
    { "$geoNear": { 
     "near": { 
      "type": "Point", 
      "coordinates": [ -73.9667, 40.78 ] 
     }, 
     "distanceField": "distance", 
     "spherical": true 
    }}, 
    { "$match": { "distance": 0 } } 
])    

所以INTIAL流水線階段返回「距離」和第二級過濾出任何結果,其中的距離實際上0

如果查詢的對象類似於「Polygon」或其他GeoJSON形式,與「精確」座標數組不匹配,那麼您應該只需要這樣做。

一般的「精確」數組匹配應該適合「點」數據。