Reputation: 1440
I am trying to find out if a document exists or not on my database, and I am kind of curious, what is the best way to do this? Using
User.findOne(query).select('_id')
or
User.count(query)
On one hand, findOne returns a 24 hexadecimal string, while count will return only an integer; on the other hand, .count
it will loop through the whole collection, while .findOne
will stop at the first matching document.
The only answer I found related to this was this question, couldn't find anything else, which answer was in favor for .count
, Mongo has done much work on performance, the question was 6 years ago.
What is more valuable? Memory (findOne) or processing power (count)?
Upvotes: 8
Views: 4759
Reputation: 39186
There are some situations where count
can give you inaccurate results. Also, the performance would be slower than the findOne()
.
On a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.
After an unclean shutdown of a mongod using the Wired Tiger storage engine, count statistics reported by count() may be inaccurate.
As you are really looking to check the existence of the document, I think findOne()
is the better option.
Upvotes: 8