Fizzix
Fizzix

Reputation: 24375

Mongodb $near returning error

I have a basic document, like so:

{ 
    "_id" : ObjectId("5760fe623f6d3ad25e387ffc"), 
    "type": 5,
    "product" : { 
         "location" : { 
              "geometry" : [ 153.39999999999998, -28.016667 ], 
              "name" : "Gold Coast QLD, Australia", 
              "id" : "ChIJt2BdK0cakWsRcK_e81qjAgM" 
          } 
    } 
}

I am trying to query the location using the $near method provided by Mongodb.

This is my query:

db.posts.find({
    'product.location.geometry': {
        $near: [ 153.39999999999998, -28.016667 ]
     }
})

Within the Mongodb documentation, it states that:

To specify a point using legacy coordinates, $near requires a 2d index and has the following syntax:

{
    $near: [ <x>, <y> ],
    $maxDistance: <distance in radians>
}

It even gives this example on their site:

db.legacy2d.find({ 
    location : { $near : [ -73.9667, 40.78 ], $maxDistance: 0.10 } 
})

This is the error it is producing:

Error: error: {
    "waitedMS" : NumberLong(0),
    "ok" : 0,
    "errmsg" : "error processing query: ns=mytestnodedb.postsTree: GEONEAR  field=product.location.geometry maxdist=1.79769e+308 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query",
    "code" : 2
}

I am unable to identify anything that is wrong with my query. Mongo states that the $near must be longitude followed by latitude, which I am definitely doing. I am purposefully leaving out $maxDistance since Mongo states that it will return results sorted from nearest to farthest.

Upvotes: 0

Views: 464

Answers (1)

Saleem
Saleem

Reputation: 8978

Well error is pretty much self explainatory. Query requires 2d index which it can't find.

I'd create index as:

db.collection.createIndex({"product.location.geometry":"2d"})

Now if I run your query on sample data, I get

{ 
    "_id" : ObjectId("5760fe623f6d3ad25e387ffc"), 
    "type" : 5.0, 
    "product" : {
        "location" : {
            "geometry" : [
                153.39999999999998, 
                -28.016667
            ], 
            "name" : "Gold Coast QLD, Australia", 
            "id" : "ChIJt2BdK0cakWsRcK_e81qjAgM"
        }
    }
}

Upvotes: 1

Related Questions