What's the fastest way to check for the existence of a mongodb doc?
Problem
What's the Fastest way to check for the existence of a mongodb doc?
Should I just use find and if it returns nothing?
EDIT:
collection.findOne {#attribute}, (err, doc) ->
if err then console.log err
if interaction
#exists
else
#does not
Solution
If you are just testing for a single document, use findOne
(or the equivalent in your driver); most drivers implement this in the most efficient possible way (by setting a negative limit of 1 on the request, which asks mongo to return immediately after finding one document, even if more might match, and not to create a cursor that won't ever be used by the client).
If you have an index that can serve your query, you can use field selection to select (a subset of) the fields in the index; this will make use of Mongo's "covered index" functionality to avoid a lookup to the underlying collection data. Be sure to set {_id: 0}
in your field selector unless _id
is in your index.
Discussion
View additional discussion.