为什么 MongoDB find 与 count 具有相同的性能
Why MongoDB find has same performance as count
我正在 运行 测试我的 MongoDB 并且出于某种原因 find
与 count
具有相同的性能。
统计:
订单集合大小:~20M,
product_id 6 的订单:~5K
product_id 已编入索引以提高性能。
查询:db.orders.find({product_id: 6})
与 db.orders.find({product_id: 6}).count()
在 0.08 毫秒后结果产品订单与 5K
为什么计数没有显着加快?它可以找到 product_id 索引
的第一个和最后一个元素位置
如 Mongo documentation for count 所述,调用 count
与调用 find
相同,但它不是 return 处理文档,而是计算它们。为了执行此计数,它遍历游标。它不能只读取索引并根据某些 ID 的第一个和最后一个值确定文档的数量,特别是因为您可以在其他一些不是 ID 的字段上建立索引(并且 Mongo ID 不是自动递增的).所以基本上 find
和 count
是相同的操作,但它不是获取文档,而是遍历它们并对它们的数字求和,然后 return 给你。
此外,如果您想要更快的结果,您可以使用 estimatedDocumentsCount
(docs) which would go straight to collection's metadata. This results in loss of the ability to ask "What number of documents can I expect if I trigger this query?". If you need to find a count of docs for a query in a faster way, then you could use countDocuments
(docs),它是聚合查询的包装器。根据我对 Mongo 的了解,提供的查询看起来是无需调用 count
即可计算查询结果的最快方法。我想这应该是从现在开始计算文档的性能的首选方式(因为它是在版本 4.0.3 中引入的)。
我正在 运行 测试我的 MongoDB 并且出于某种原因 find
与 count
具有相同的性能。
统计: 订单集合大小:~20M, product_id 6 的订单:~5K
product_id 已编入索引以提高性能。
查询:db.orders.find({product_id: 6})
与 db.orders.find({product_id: 6}).count()
在 0.08 毫秒后结果产品订单与 5K
为什么计数没有显着加快?它可以找到 product_id 索引
的第一个和最后一个元素位置如 Mongo documentation for count 所述,调用 count
与调用 find
相同,但它不是 return 处理文档,而是计算它们。为了执行此计数,它遍历游标。它不能只读取索引并根据某些 ID 的第一个和最后一个值确定文档的数量,特别是因为您可以在其他一些不是 ID 的字段上建立索引(并且 Mongo ID 不是自动递增的).所以基本上 find
和 count
是相同的操作,但它不是获取文档,而是遍历它们并对它们的数字求和,然后 return 给你。
此外,如果您想要更快的结果,您可以使用 estimatedDocumentsCount
(docs) which would go straight to collection's metadata. This results in loss of the ability to ask "What number of documents can I expect if I trigger this query?". If you need to find a count of docs for a query in a faster way, then you could use countDocuments
(docs),它是聚合查询的包装器。根据我对 Mongo 的了解,提供的查询看起来是无需调用 count
即可计算查询结果的最快方法。我想这应该是从现在开始计算文档的性能的首选方式(因为它是在版本 4.0.3 中引入的)。