This question already has an answer here:
- Difference between count() and find().count() in MongoDB 5 answers
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?