查找 mongo 文档计数的最佳做法是啥?

Posted

技术标签:

【中文标题】查找 mongo 文档计数的最佳做法是啥?【英文标题】:What is the best practice to find mongo documents count?查找 mongo 文档计数的最佳做法是什么? 【发布时间】:2021-07-23 19:02:08 【问题描述】:

想知道countDocument和find查询的性能差异。

我必须根据特定的过滤器找到文档的数量,哪种方法更好并且花费更少的时间?

db.collection.countDocuments( userId: 12 )

db.collection.find( userId: 12 ) 然后使用结果数组的长度。

【问题讨论】:

【参考方案1】:

如果您不需要数据,您绝对应该使用db.collection.countDocuments()。此方法使用 aggregation 管道和您传递的过滤器,并且只返回计数,因此您不会浪费处理和时间等待包含所有结果的数组。

这个:

db.collection.countDocuments( userId: 12 )

相当于:

db.collection.aggregate([
    $match:  userId: 12  ,
    $group:  _id: null, n:  $sum: 1   
])

【讨论】:

感谢 Rafael 的回答。

以上是关于查找 mongo 文档计数的最佳做法是啥?的主要内容,如果未能解决你的问题,请参考以下文章