Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb find query with $near and coordinates not working

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!

like image 200
DeaIss Avatar asked Apr 05 '14 13:04

DeaIss


People also ask

How is querying done in MongoDB using Find ()?

find() with Example. The method of fetching or getting data from a MongoDB database is carried out by using MongoDB queries. While performing a query operation, one can also use criteria's or conditions which can be used to retrieve specific data from the database. MongoDB provides a function called db.

Does MongoDB support geospatial index?

MongoDB provides the following geospatial index types to support the geospatial queries.

How do I search for a query in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

How $or works in MongoDB?

MongoDB provides different types of logical query operators and $or operator is one of them. This operator is used to perform logical OR operation on the array of two or more expressions and select or retrieve only those documents that match at least one of the given expression in the array.


1 Answers

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.

like image 57
John Powell Avatar answered Oct 25 '22 03:10

John Powell