mongodb count vs.count with count [英] mongodb count vs find with count
问题描述
我正在对mongo(版本2.4和3.2)集合中的文档进行计数.馆藏非常大,共有3,820,085个文档.我需要计算所有引用为_id
的文档.我尝试了两个不同的查询:
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")})
此查询需要很长时间.太多的时间让我没有完成,超过5分钟,我被吓到要杀死它.
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.
对于此集合field._id
不是索引.我没有与此查询一起使用索引的相关信息.
For this collection field._id
is not an index. I do not have relevant info to use an index with this query.
是否有更好的方法来计算mongo中的文档.
Is there a better approach to count document in mongo.
更新:
我了解我需要在字段field._id
上建立索引.如果我确实有该字段的索引,那么在大集合db.SampleCollection.find(...).count()
或db.SampleCollection.count(...)
上哪种方法会更好?还是两者没有区别?
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?
推荐答案
在您的方案中,您应该有一个索引.
In your scenario, you should have an index.
索引支持在MongoDB中高效执行查询.没有索引,MongoDB必须执行集合扫描,即扫描集合中的每个文档,以选择与查询语句匹配的那些文档.
https://docs.mongodb.com/manual/indexes/
更新:
现在提出的问题有所不同. "collection.find({}).count()"比"collection.count()"更快吗?
the question asked now is different. Is "collection.find({}).count()" more fast then "collection.count()"?
根据MongoDB文档:
According to the MongoDB documentation:
count()等效于db.collection.find(query).count()构造. https://docs.mongodb.com/manual/reference/method/db.collection.count/
这篇关于mongodb count vs.count with count的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!