I've read sources that say MongoDB's findOne()
is much slower than find().limit(1)
, but then I've also heard otherwise. What's actually the current truth?
Article from March 2013: "It is significantly 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."
SE answer from 2011: "If the find().limit(1) document is retrieved, the orders of magnitude speed difference seems to disappear. Also, I could not reproduce the major speed difference with the MongoDB JavaScript driver. I originally benchmarked using the MongoDB Java driver."
I hope whatever the answer is, it is also consistent with using Mongoose's find().sort().limit(1)
and findOne()
.
The findOne() returns first document if query matches otherwise returns null. The find() method does not return null, it returns a cursor. There is no document present in the above collection.
Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.
The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.
MongoDB findOne() method returns only one document that satisfies the criteria entered. If the criteria entered matches for more than one document, the method returns only one document according to natural ordering, which reflects the order in which the documents are stored in the database.
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.
find()
returns a cursor whereas findOne()
returns the exact document.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
.limit(-1)
and limit(0)
limit()
value of 0 (i.e. .limit(0)
) is equivalent to setting no limit.For more information, you can refer the official block: http://docs.mongodb.org/manual/reference/method/cursor.limit/]1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With