【问题标题】:Why does MongoDB count so long?为什么 MongoDB 算这么长?
【发布时间】:2017-07-17 19:46:13
【问题描述】:

我收集了大约 2 000 000 个文档。 字段unit 具有索引:{"unit" : 1.0}

查询:

db.getCollection('CollectionName').find({"unit":"value"}).count()

执行 5 秒(结果 200 000 个文档)

查询:

db.getCollection('CollectionName').find({"unit":"value"})

执行 0.005 秒

为什么?

【问题讨论】:

    标签: mongodb indexing count


    【解决方案1】:

    find() 返回一个游标,find().count() 耗尽该游标以计算其中的文档数。

    您可能更喜欢使用db.collection.count,例如:

    db.getCollection('CollectionName').count({"unit":"value"})
    

    【讨论】:

    • db.collection.count 等价于 db.collection.find
    • 功能上等效,但非功能性不同。 find(...).count() 将读取所有 200,000 个文档,然后对它们进行计数,而 count(...) 将在服务器端执行计数,并且仅返回与给定过滤器匹配的文档数。
    • db.getCollection('CollectionName').count({"unit":"value"}) 没有帮助,查询执行 5 秒
    • 如果您运行的版本 >= 3.0,那么您可以尝试explaining the count,例如:db.getCollection('CollectionName').explain().count({"unit":"value"})。但是,基本的一点仍然是,当您将countfind 的任何一种形式进行比较时,您可能没有进行有效的比较,因为find 只返回一个游标,而count 实际上是在读取数据并计算响应。
    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 2022-08-04
    • 2015-11-11
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    相关资源
    最近更新 更多