My problem is: There is a collection of users. Im trying to find, does user with _id=xxx
has somevalue > 5
.
I'm wondering, what will be faster, using find(...).count() > 0
or findOne(...) != null
? Or maybe there is some other, faster/better way?
The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and the other is optional.
MongoDB does have an optimisation for a fast count where all the queried fields are indexed and the query is based around equivalence, but only in that circumstance. The road to performance can often be found by stepping back and looking at the wider problem.
The findOne() method finds and returns one document that matches the given selection criteria. If multiple documents satisfy the given query expression, then this method will return the first document according to the natural order which reflects the order of documents on the disk.
The findOne() returns first document if query matches otherwise returns null. The find() method does not return null, it returns a cursor.
The difference between the query times should be almost negligible, because they both limit the bounds of the unique _id, so they will be found immediately. The only slight edge here goes to the count
because the db will return a int instead of an entire document. So the time you save is purely because of the transfer of the data from db to client.
That being said, if your goal is to do an exists query and you don't care about the data, use the count
Using count() does not pin the document, in contrary to find(), to the cache, which saves you memory. Memory is your most valuable resource, when using mongodb or any other DB... besides a fast disk.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With