2017-01-01 77 views
0

我使用Mongo DB來存儲座標,我想使用$ near query查找座標,但沒有結果,有人可以幫我嗎? 這裏是我的蒙戈DB

> db.course.getIndexes() 
[ 
    { 
      "v" : 1, 
      "key" : { 
        "_id" : 1 
      }, 
      "name" : "_id_", 
      "ns" : "dev.course" 
    }, 
    { 
      "v" : 1, 
      "key" : { 
        "coordinate" : "2dsphere" 
      }, 
      "name" : "coordinate_2dsphere", 
      "ns" : "dev.course", 
      "2dsphereIndexVersion" : 3 
    } 
] 

指數這裏是我的數據

{ "_id" : 1, "schoolId" : 0, "longitude" : 0, "latitude" : 0, "coordinate" : [ 0, 0 ], "courseTitle" : "暫無", "imageIds" : "[]", "videoIds" : "[]", "startTime" : "", "teacherIds" : "[]", "gradeIds" : "[]", "subjectId" : 0, "expense" : 0, "followNum" : 0, "courseStatus" : "NOSTART", "authorizationStatus" : "NO", "rejectReason" : "", "createTime" : "2017-01-01 16:58:22" } 

我查詢

db.course.find({"coordinate": {"near": [123, 20]}}) 

沒有結果。有誰能夠幫助我?

回答

0

$near是運營商使用,如果你寫near它只會匹配near字段下的coordinate字段。

$near請求將是這樣的:

db.course.find({ 
    "coordinate": { 
     "$near": { 
      $geometry: { 
       type: "Point", 
       coordinates: [123, 20] 
      } 
     } 
    } 
}) 

要使用2dsphere索引文件應該GeoJSON格式需要的其它附加type領域:

{ type: "<GeoJSON type>" , coordinates: <coordinates> } 

所以,你只需要更換"coordinate" : [ 0, 0 ]附:

"coordinate": { 
    type: "Point", 
    coordinates: [0, 0] 
} 
+0

它的作品,非常感謝你!如果我使用2dsphere索引文件,那麼我必須使用GeoJSON格式,但如果我使用2d索引文件,那麼我可以使用GesJSON和傳統座標對,是嗎? – Minky

+0

你能告訴我這個查詢有什麼問題:> db.course.find({「coordinate」:{「$ near」:[123,20],「$ limit」:100}}) – Minky

+0

是2d用於遺留座標,2dspere爲GeoJSon格式。你可以用'db.course.find({「coordinate」:{「$ near」:[123,20]}})來限制結果的數量,限制(100)' –