Find location with $nearSphere

Just trying to follow the tutorial https://www.mongodb.com/docs/manual/tutorial/geospatial-tutorial/#sorted-with--nearsphere

I’ve followed every step, until the last one:

Sorted with $nearSphere
You may also use $nearSphere and specify a $maxDistance term in meters. This will return all restaurants within five miles of the user in sorted order from nearest to farthest:

Which I got:

var METERS_PER_MILE = 1609.34

db.restaurants.find({ location: { $nearSphere: { $geometry: { type: "Point", coordinates: [ -73.93414657, 40.82302903 ] }, $maxDistance: 5 * METERS_PER_MILE } } })
Uncaught:
MongoServerError: error processing query: ns=test.restaurantsTree: GEONEAR  field=location maxdist=8046.7 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error :: caused by :: unable to find index for $geoNear query

Yet, finding the very location with $geoWithin works as expected:

db.restaurants.find({ location: { $geoWithin: { $centerSphere: [[-73.93414657, 40.82302903], 5 / 3963.2] } } })

...
  {
    _id: ObjectId("55cba2476c522cafdb053b24"),
    location: { coordinates: [ -73.9805679, 40.7659436 ], type: 'Point' },
    name: 'Cafe Atelier (Art Students League)'
  },
  {
    _id: ObjectId("55cba2476c522cafdb053b25"),
    location: { coordinates: [ -73.965531, 40.765431 ], type: 'Point' },
    name: "Donohue'S Steak House"
  }
]
Type "it" for more

What might be the problem? thx

Hello @MBee ,

I was able to replicate the error after I deleted the 2dsphere index.

As mentioned in the Documentation

A geospatial index, and almost always improves performance of $geoWithin and $geoIntersects queries.

Because this data is geographical, create a 2dsphere index on each collection using mongosh:

db.restaurants.createIndex({ location: "2dsphere" })
db.neighborhoods.createIndex({ geometry: "2dsphere" })

Kindly create the index and try again.

Let me know in case you face any issues, would be happy to help you! :slight_smile:

Regards,
Tarun

Yep. I missed the creating 2dsphere index step, and having created the index everything works when I tried again.

Thanks!

BTW, I’ve followed every step in the tutorial https://www.mongodb.com/docs/manual/tutorial/geospatial-tutorial/#sorted-with--nearsphere, until the last one.

I.e., it’s interesting that all commands except the last one work without a 2dsphere index :slight_smile: .

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.