Checking if a document exists – MongoDB slow findOne vs find

By
David Mytton,
CEO & Founder of Server Density.
Published on the 14th March, 2013.
One of the biggest optimisations to make MongoDB writes faster is to avoid moving documents by doing updates in place to a preallocated document. You only want to preallocate if the document doesn’t exist and to check this you need to do a query.
The findOne()
method seems like the right choice for this because you can query the relevant index and check to see if a document or None
is returned, ideally using a covered index.
However, 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.
So instead of:
db.collection.findOne({_id: "myId"}, {_id: 1})
you should use:
db.collection.find({_id: "myId"}, {_id: 1}).limit(1)
By making this change I saw a change in performance of 2 orders of magnitude: