You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取MongoDB聚合$count阶段返回的totalCount数值

MongoDB聚合$count结果读取方法

核心原因

你调用aggregate拿到的cursorTest是MongoDB游标对象,并没有直接存储聚合结果,需要通过游标提供的方法读取内部的结果文档。你追加$count阶段后,聚合结果最多只会返回1个包含totalCount字段的文档,可以通过以下几种方式获取数值:


方法1:async/await + toArray(最常用)

async function getCount() {
  pipelineTest.push({$count: "totalCount"});
  const cursorTest = collection.aggregate(pipelineTest, options);
  // 将游标内所有结果转为数组
  const resultArr = await cursorTest.toArray();
  // 取第一条文档的totalCount字段,无匹配结果时默认返回0
  const totalCount = resultArr[0]?.totalCount || 0;
  console.log(totalCount);
}

方法2:async/await + next(性能更优)

因为$count阶段最多返回1条结果,直接用next()取单条结果无需转换整个数组,性能更高:

async function getCount() {
  pipelineTest.push({$count: "totalCount"});
  const cursorTest = collection.aggregate(pipelineTest, options);
  const resultDoc = await cursorTest.next();
  const totalCount = resultDoc?.totalCount || 0;
  console.log(totalCount);
}

方法3:回调函数方式

如果你的项目用回调风格处理异步逻辑,可以用以下写法:

pipelineTest.push({$count: "totalCount"});
collection.aggregate(pipelineTest, options).toArray(function(err, resultArr) {
  if (err) throw err;
  const totalCount = resultArr[0]?.totalCount || 0;
  console.log(totalCount);
});

内容的提问来源于stack exchange,提问作者Aux98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 06:36:01