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 }
相关推荐
芝士爱知识a30 分钟前
【FinTech前沿】AlphaGBM:重塑期权交易的智能分析引擎——从原理到实践
数据结构·数据库·人工智能·alphagbm·期权
AC赳赳老秦30 分钟前
2026主权AI趋势:DeepSeek搭建企业自有可控AI环境,保障数据安全实战
大数据·数据库·人工智能·python·科技·rabbitmq·deepseek
仍然.33 分钟前
MYSQL---事务
数据库·mysql
king_harry38 分钟前
openGauss 6.0 主备集群备份与恢复实战指南:基于 gs_probackup
数据库·opengauss·gs_probackup
ruxshui1 小时前
MySQL备份核心指南
数据库·mysql
霖霖总总1 小时前
[小技巧73]MySQL UUID 全面解析:UUID 的原理、结构与最佳实践
数据库·mysql
tod1132 小时前
Redis C++ 客户端开发全流程指南
数据库·c++·redis·缓存
w_t_y_y2 小时前
MySQL原理(三)锁定机制(4)常见的行锁行为&影响哪些操作&对DB的影响
数据库
沧澜sincerely2 小时前
组合查询(UNION)
数据库·union·union all