1

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

Alex Blex
  • 25,038
  • 5
  • 33
  • 63
Amit be
  • 419
  • 2
  • 13

1 Answers1

1

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)

alekseys
  • 315
  • 1
  • 6
  • Very strange, i'm using almost the same query and i can see limit is being ignored. The location property on my db looks like that: ` "location": { "type": "Point", "coordinates": [ 34.780659466136484, 32.08260571073972 ] }` maybe it is a format issue? – Amit be Nov 21 '17 at 14:33
  • It also might be related to the fact my query is on "location" and not "location.coordinates"? I get 0 results on "location.coordinates" – Amit be Nov 22 '17 at 07:10
  • play around with minDistance and maxDistance values - you might not be getting an overlap with the shape they're defining. – alekseys Nov 22 '17 at 23:28