Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb count vs findone

Tags:

mongodb

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?

like image 360
Bugari Avatar asked Jun 27 '12 18:06

Bugari


People also ask

What is count () in MongoDB?

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.

Is count fast MongoDB?

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.

What is MongoDB findOne?

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.

What is the difference between find and findOne in MongoDB?

The findOne() returns first document if query matches otherwise returns null. The find() method does not return null, it returns a cursor.


2 Answers

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

like image 150
jdi Avatar answered Oct 18 '22 21:10

jdi


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.

like image 1
user1967880 Avatar answered Oct 18 '22 20:10

user1967880