Mongodb check existence count vs findOne performance
Asked Answered
B

1

8

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)?

Blakley answered 6/2, 2018 at 18:21 Comment(0)
A
7

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.

Azygous answered 6/2, 2018 at 18:32 Comment(3)
Just want to refer to this post: blog.serverdensity.com/… It's telling the opposite, although they don't use count().Isoagglutination
On a sharded cluster, db.collection.count() without a query predicate can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress. - db.collection.count()Indoaryan
@Isoagglutination the blogpost claims find.limit(1) is faster than findOne. This answer claims that's 'arguably benchmarking useless code' https://mcmap.net/q/561178/-what-39-s-faster-find-limit-1-or-findone-in-mongodb-mongoose Does anyone have reproducible benchmark examples?Merrie

© 2022 - 2024 — McMap. All rights reserved.