7

What does a negative value for limit operator mean?

http://www.mongodb.org/display/DOCS/Aggregation+Framework+-+$limit

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D

Mongo returns the same exact document when I do limit(1) or limit(-1) ??

kapso
  • 11,703
  • 16
  • 58
  • 76
  • It sounds to me like mongo is taking the absolute value of the limit you enter. Which is good because a negative limit makes no sense. – Tim Gautier Aug 16 '12 at 18:36
  • possible duplicate of [In a MongoDB query, what does a negative limit mean?](http://stackoverflow.com/questions/9833941/in-a-mongodb-query-what-does-a-negative-limit-mean) – Dan Dascalescu Mar 02 '14 at 03:38

2 Answers2

16

If the limit number is negative, then generally the database will return that number of results and close the cursor - essentially a single batch of results is returned and no further results for that query can be fetched.

As for the less general case, if the negative limit value exceeds the batch size (particularly the max batch size), then the batch will be returned and the cursor closed whether the limit has been reached or not. Hence, the single batch rule trumps the limit specified if the limit is too high.

If the limit is positive you can leave the cursor open to receive further results and continue to iterate until the cursor is exhausted.

For more on batches and cursors, take a look here:

http://docs.mongodb.org/manual/core/cursors/#cursor-batches http://docs.mongodb.org/manual/reference/method/cursor.limit/#negative-values

Adam Comerford
  • 21,336
  • 4
  • 65
  • 85
  • 1
    Thanks, so is one option more efficient than the other? – kapso Aug 16 '12 at 21:35
  • 2
    If you are retrieving exactly that number of results, your limit is greater than 1, and you are under the batch size limit (believe the default is 101, but adjustable - see the link in my answer and the batches section), then the negative limit may be beneficial. Otherwise, there might be problems with using a negative limit - the true way to tell, as always, is to test with your data set. – Adam Comerford Aug 17 '12 at 00:20
-3

you must send a negative value for limit to mongodb like :

 const options = {
        page: req.query.page || 0,
        limit: -20,
    };