MongoDB 'unable to find index for $geoNear query'

Solution 1:

Few problems, you created your indexes on the foo collection of the foo database, but are querying the bar collection. You need to be on the correct collection.

Reading the document you have inserted you need to add a "2dsphere" index to support the geoJson objects. This index needs to be on the "point" element of your documents, so try

db.bar.createIndex({point:"2dsphere"});

You can then query as follows by providing a geoJson obj for the query:

db.bar.find(
   { point :
       { $near :
          {
            $geometry : {
               type : "Point" ,
               coordinates : [-84.27326978424058, 30.443902444762696] },
            $maxDistance : 1
          }
       }
    }
)

Solution 2:

db.prod.createIndex({ "location": "2d" })

This solved for the same issue for me.

Where prod is my collection name and location is name of column which stores geo location (GeoPoint)

Some discussion about the same can be found here

Solution 3:

So there seems to be a couple of things wrong here:

  • From the data you are showing and also your query information the relevant information is contained under the field point and in GeoJSON format. Your index creation:
db.foo.createIndex({geo: "2d"})

Does not "fail" because there presently isn't a field called "geo" and the field with the data should have been in that place. If you had used "point" instead, which is the correct field, then you would have received an error telling you that this type of index is invalid for the GeoJSON data. You need a "2dsphere" index:

db.points.createIndex({ "point": "2dsphere" })
  • Extending the same problem, again the data is in GeoJSON format and the form of the query is that for a legacy coordinate pair. You need to change the query arguments so that no longer fails:
db.points.find({point: {
    $near: {
        $geometry:{ 
            type: "Point", 
            coordinates: [-84.26060492426588, 30.45023887165371]
        }
    }
}})

See the documentation for $near

Solution 4:

In addition to the answers above, if you've already tried to create an Index and got some syntax or field wrong, you can run

db.<yourcollection>.dropIndexes(); To clean up all indexes and re-create them properly.

Also, the index should be created on the parent of "coordinates", not on coordinates itself:

{
   "_id": 59ac03d168eaaa14c2a57a00",
   "location":{
      "type":"Point",
      "coordinates":[
         131.6667,
         57.8368
      ]
   },
   "age":53,
   "username":"Brandi_Greenfelder"
}

db.<yourcollection>.createIndex({ location: '2dsphere' });

Attention, there is "2d" and "2dsphere", use the second as it's the new thing.