What's faster: `find().limit(1)` or `findOne()` in MongoDB/Mongoose? What's faster: `find().limit(1)` or `findOne()` in MongoDB/Mongoose? mongodb mongodb

What's faster: `find().limit(1)` or `findOne()` in MongoDB/Mongoose?


Both are equally fast.

When you do find().limit(1) no query is send to the server. You just prepare the query client side. As long as you don't retrieve any documents you can still modify the cursor, thus the query (eg by adding a sort).

So if you benchmark only the find().limit(1) you'll find it's a lot faster, because the query isn't executed. Arguably you're benchmarking useless code.


db.collection.findOne() Vs db.collection.find().limit(1)

  • find() returns a cursor whereas findOne() returns the exact document.
  • It is faster to use find() + limit() because findOne() will always read + return the document if it exists.
  • find() just returns a cursor (or not) and only reads the data if you iterate through the cursor.
  • find() has a cursor and hence you can use explain() with your query in the mongo shell to see the winning plan and other details on the execution of your query.

Extra: limit(-1) and limit(0)

  • A limit() value of 0 (i.e. .limit(0)) is equivalent to setting no limit.
  • A negative limit is similar to a positive limit but closes the cursor after returning a single batch of results.

For more information, you can refer the official block: http://docs.mongodb.org/manual/reference/method/cursor.limit/]1