Reputation: 121
I am using Mongo DB to store coordinates and I want to find coordinates using $near query, but I got no result, can anybody help me? Here is my index of mongo 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
}
]
Here is my data
{ "_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" }
My query is
db.course.find({"coordinate": {"near": [123, 20]}})
There is no result. Can anybody help me?
Upvotes: 0
Views: 183
Reputation: 45352
$near
is the operator to use, if you write near
it will only match a field named near
under coordinate
field.
The $near
request would be like :
db.course.find({
"coordinate": {
"$near": {
$geometry: {
type: "Point",
coordinates: [123, 20]
}
}
}
})
To use 2dsphere
index the document should be of GeoJSON
format which needs an additionnal type
field :
{ type: "<GeoJSON type>" , coordinates: <coordinates> }
So you just need to replace "coordinate" : [ 0, 0 ]
with :
"coordinate": {
type: "Point",
coordinates: [0, 0]
}
Upvotes: 1