MongoDB聚合:$count

$count阶段用于统计管道中文档的数量。

语法

js 复制代码
{ $count: <string> }

<string> 是文档计数输出字段的名称。<string>必须是非空字符串,不能以$开头,也不能包含.字符。

$count阶段相当于下面$group+$project聚合序列:

js 复制代码
db.collection.aggregate( [
   { $group: { _id: null, myCount: { $sum: 1 } } },
   { $project: { _id: 0 } }
] )

其中myCount是包含计数的输出字段。也可以为输出字段指定其他名称。

举例

"scores"的集合有以下文档:

json 复制代码
{ "_id" : 1, "subject" : "History", "score" : 88 }
{ "_id" : 2, "subject" : "History", "score" : 92 }
{ "_id" : 3, "subject" : "History", "score" : 97 }
{ "_id" : 4, "subject" : "History", "score" : 71 }
{ "_id" : 5, "subject" : "History", "score" : 79 }
{ "_id" : 6, "subject" : "History", "score" : 83 }

下面的汇总操作分为两个阶段:

  1. $match阶段会排除分值小于或等于80的文档,将分值大于80的文档传递到下一阶段。

  2. $count阶段返回聚合管道中剩余文档的计数,并将该值赋值给名为passing_scores的字段。

js 复制代码
db.scores.aggregate(
  [
    {
      $match: {
        score: {
          $gt: 80
        }
      }
    },
    {
      $count: "passing_scores"
    }
  ]
)

操作返回以下结果:

json 复制代码
{ "passing_scores" : 4 }
相关推荐
m0_515098421 分钟前
Redis怎样强行终止陷入死循环的Lua脚本
jvm·数据库·python
2301_817672262 分钟前
SQL中RIGHT JOIN真的很少用吗_数据完整性检查与反向关联分析
jvm·数据库·python
2501_914245935 分钟前
mysql如何进行表空间传输恢复_mysql transport tablespace实战
jvm·数据库·python
qq_330037998 分钟前
MongoDB的聚集索引怎么用_Clustered Collections的插入性能优化
jvm·数据库·python
qq_3345635514 分钟前
html标签怎么表示用户输入_kbd标签键盘快捷键标注【介绍】.txt
jvm·数据库·python
小陈工14 分钟前
数据库Operator开发实战:以PostgreSQL为例
开发语言·数据库·人工智能·python·安全·postgresql·开源
weixin_5860614614 分钟前
SQL报表星型模型优化_事实表索引设计
jvm·数据库·python
数智化管理手记24 分钟前
零基础认知精益生产——核心本质与必避误区
大数据·数据库·人工智能·低代码·制造
weixin_3812881825 分钟前
MongoDB备节点无法读取数据怎么解决_rs.slaveOk()与Secondary读取权限
jvm·数据库·python
qq_6543669829 分钟前
Vue 3 中集成 Three.js 场景的完整实践指南
jvm·数据库·python