using $nearSphere + limit in a mongodb find query

424 Views Asked by At

I've created a query with $nearSphere and I realized that I get sometimes enormous amount of results (1000+), which affects my app's performance.

I've tried to use .limit() but it seems to be ignored by the query. I also tried to use batch_size() and it doesn't seem to affect the number of the results returned at all.

Is there any kind of hack or a way to limit the results returned? I thought about execution with an iterator, this is what I've and it doesn't seem great for performance:

for r in xrange(0,limit):
        print res.next()

The query itself is quite simple:

query = {"location": {
    "$nearSphere": {"$geometry": {"type": "Point", "coordinates"
     [geo['lat'], geo['lng']]}, "$maxDistance": 500}}}


coll.find(query).limit(4).batch_size(4)

I'm using the Mongodb API on Azure Cosmos-db

1

There are 1 best solutions below

3
alekseys On

I cannot repro this issue. Limit works just fine. Try to use the example doc (make few copies of it in the same collection) from https://aka.ms/mongodb-feature-support and the query from the docs and append .limit(1) to it to see the correct behavior:

db.volcanos.find({ "Location.coordinates": { $nearSphere : { $geometry: {type: "Point", coordinates: [ -121, 46 ]}, $minDistance: 1000, $maxDistance: 1000000 } } }).limit(1)