Mongodb find query with $near and coordinates not working

DeaIss picture DeaIss · Apr 5, 2014 · Viewed 11.1k times · Source

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!

Answer

John Powell picture John Powell · Apr 5, 2014

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.