Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a MongoDB query, what does a negative limit mean?

I'm using the Mongoid ruby gem to interact w/ MongoDB and when I try to get one of something from a query, it adds $limit: -1 (i.e. negative one) when I would expect it to just use 1. I tried doing the same thing in the console and it didn't change which document was returned.

Does a negative limit mean something special?

like image 418
nicholaides Avatar asked Mar 23 '12 03:03

nicholaides


People also ask

What does limit do in MongoDB?

In MongoDB, the limit() method limits the number of records or documents that you want. It basically defines the max limit of records/documents that you want. Or in other words, this method uses on cursor to specify the maximum number of documents/ records the cursor will return.

How do I limit query results in MongoDB?

The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.

What is the limitation of a document in MongoDB?

The maximum BSON document size is 16 megabytes. The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth. To store documents larger than the maximum size, MongoDB provides the GridFS API.

What is difference between limit and skip in MongoDB?

The limit method will be used to return the maximum number of results from the collection, while the skip method is used to skip the number of documents from the collection in MongoDB.


2 Answers

There is a note on negative limits under the "numberToReturn" heading in the "OP_QUERY" section of the "Mongo Wire Protocol" documentation.

"If the client driver offers 'limit' functionality (like the SQL LIMIT keyword), then it is up to the client driver to ensure that no more than the specified number of document are returned to the calling application. If numberToReturn is 0, the db will used the default return size. If the number is negative, then the database will return that number and close the cursor. No further results for that query can be fetched."

For more information on cursors and limit, please see the "Queries and Cursors" documentation, specifically the now-removed "Execution of queries in batches" section.

like image 158
Marc Avatar answered Oct 07 '22 06:10

Marc


The sign of the limit value determines whether its a 'hard limit' or a 'soft limit'. A 'hard limit' (negative sign) query closes the cursor after it has returned the maximum number of documents it can. A 'soft limit' keeps the cursor open in case the response can not fit as many documents as specified by the limit.

like image 21
Yasser Avatar answered Oct 07 '22 07:10

Yasser