Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb count vs find with count [duplicate]

Tags:

mongodb

nosql

I am performing a count of documents in a mongo (versions 2.4 and 3.2) collection. The collection is very big, 3821085 documents. I need to count all documents with a reference _id. I have tried two different queries:

db.SampleCollection.find({"field._id" : ObjectId("UUID")}).count() db.SampleCollection.count({"field._id" : ObjectId("UUID")})

This query takes a very long time. So much time that I have not let it complete, more than 5 minutes and I get scared and kill it.

For this collection field._id is not an index. I do not have relevant info to use an index with this query.

Is there a better approach to count document in mongo.

UPDATE:

I understand that I need an index on the field field._id. If I did have an index for the field which approach would perform better on a large collection db.SampleCollection.find(...).count() or db.SampleCollection.count(...)? Or is there no difference between the two?

like image 834
soundslikeodd Avatar asked Oct 15 '16 16:10

soundslikeodd


People also ask

Is count faster than find MongoDB?

collection. count() without parameters counts all documents in a collection whereas db. collection. find() without parameters matches all documents in a collection, and appending count() counts them, so there is no difference.

What is countDocuments MongoDB?

In MongoDB, the countDocuments() method counts the number of documents that matches to the selection criteria. It returns a numeric value that represents the total number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and other is optional.

What does count return on MongoDB?

count() The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria.

How do I search multiple values in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.


1 Answers

In your scenario, you should have an index.

Indexes

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement.

UPDATE:

the question asked now is different. Is collection.find({}).count() more fast then collection.count()?

According to the MongoDB documentation:

db.collection.count()

count() is equivalent to the db.collection.find(query).count() construct.

like image 151
Daniele Tassone Avatar answered Oct 09 '22 23:10

Daniele Tassone