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 }
相关推荐
zuoerjinshu4 小时前
sql实战解析-sum()over(partition by xx order by xx)
数据库·sql
NocoBase5 小时前
【2.0 教程】第 1 章:认识 NocoBase ,5 分钟跑起来
数据库·人工智能·开源·github·无代码
Hoshino.417 小时前
基于Linux中的数据库操作——下载与安装(1)
linux·运维·数据库
Oueii8 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
未来龙皇小蓝9 小时前
【MySQL-索引调优】11:Group by相关概念
数据库·mysql·性能优化
2401_831824969 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python
njidf9 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
twc8299 小时前
大模型生成 QA Pairs 提升 RAG 应用测试效率的实践
服务器·数据库·人工智能·windows·rag·大模型测试
@我漫长的孤独流浪9 小时前
Python编程核心知识点速览
开发语言·数据库·python
2401_851272999 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python