Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: truth behind find({...}).limit(#)

In MongoDB, does .find({...}).limit(#) really limit the number of queries?

I mean, when you do db.collection.find(condition), doesn't it already waste computational power to query all the results that match the given condition? If so, then does adding .limit() after it just strip off the unneeded elements from the query results?

Thanks a lot for clarifying this up!

like image 370
Maria Avatar asked Mar 14 '26 09:03

Maria


1 Answers

db.collection.find returns a cursor, not an array of results or similar. From the documentation:

When the find() method “returns documents,” the method is actually returning a cursor to the documents.

The documents are actually located when you iterate the cursor. So calling .limit tells the cursor when to say it's done iterating.

More about cursors here: http://docs.mongodb.org/manual/core/cursors/#read-operations-cursors

like image 169
T.J. Crowder Avatar answered Mar 15 '26 22:03

T.J. Crowder