问题
I'm trying to make use of some geolocation functionality in mongodb. Using a find query with $near doesn't seem to work!
I currently have this object in my database:
{
"Username": "Deano",
"_id": {
"$oid": "533f0b722ad3a8d39b6213c3"
},
"location": {
"type": "Point",
"coordinates": [
51.50998,
-0.1337
]
}
}
I have the following index set up as well:
{
"v": 1,
"key": {
"location": "2dsphere"
},
"ns": "heroku_app23672911.catchmerequests",
"name": "location_2dsphere",
"background": true
}
When I run this query:
db.collectionname.find({ "location" : { $near : [50.0 , -0.1330] , $maxDistance : 10000 }})
I get this error:
error: {
"$err" : "can't parse query (2dsphere): { $near: [ 50.0, -0.133 ], $maxDistance: 10000.0 }",
"code" : 16535
}
Does anyone know where I'm going wrong? Any help would be much appreciated!
回答1:
It seems you need to use the GeoJSON format if your data is in GeoJSON format too, as yours is. If you use:
db.collectionname.find({
"location": {
$near: {
$geometry:
{ type: "Point", coordinates: [50.0, -0.1330] }, $maxDistance: 500
}
}
})
it should work. I could replicate your error using GeoJSON storage format for the field, but what the docs call legacy points in the query expression. I think the docs are a bit unclear in that they suggest you can use both GeoJSON and legacy coordinates with a 2dsphere index 2dsphere
I am using 2.4.10, for what it is worth, as there were some big changes to spatial in the 2.4 release.
回答2:
This isn't exactly a solution as I never got the above working, but using geoNear I managed to get what I wanted.
db.runCommand( { geoNear : 'catchmerequests', near:
{ type: 'Point', coordinates : [50, 50] }, spherical : true } );
If anyone can find out why the original $near attempt failed that would still be appreciated, but I'm posting this for anyone else who else who is looking for a working alternative.
来源:https://stackoverflow.com/questions/22881401/mongodb-find-query-with-near-and-coordinates-not-working