What's Faster: `find().limit(1)` Or `findone()` In Mongodb/mongoose?
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:
Solution 1:
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.
Solution 2:
db.collection.findOne() Vs db.collection.find().limit(1)
find()
returns a cursor whereasfindOne()
returns the exact document.- It is faster to use
find() + limit()
becausefindOne()
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 acursor
and hence you can useexplain()
with your query in the mongo shell to see the winning plan and other details on the execution of yourquery
.
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
Post a Comment for "What's Faster: `find().limit(1)` Or `findone()` In Mongodb/mongoose?"