支持端:小程序 2.7.4, 云函数 0.8.1, Web
聚合阶段。计算上一聚合阶段输入到本阶段的记录数,输出一个记录,其中指定字段的值为记录数。
count 的形式如下:
count(<string>)
<string> 是输出记录数的字段的名字,不能是空字符串,不能以 $ 开头,不能包含 . 字符。
count 阶段等同于 group + project 的操作:
const $ = db.command.aggregate
db.collection('items').aggregate()
  .group({
    _id: null,
    count: $.sum(1),
  })
  .project({
    _id: 0,
  })
  .end()
上述操作会输出一个包含 count 字段的记录。
假设集合 items 有如下记录:
{
  _id: "1",
  price: 10.5
}
{
  _id: "2",
  price: 50.3
}
{
  _id: "3",
  price: 20.8
}
{
  _id: "4",
  price: 80.2
}
{
  _id: "5",
  price: 200.3
}
找出价格大于 50 的记录数:
const $ = db.command.aggregate
db.collection('items').aggregate()
  .match({
    price: $.gt(50)
  })
  .count('expensiveCount')
  .end()
返回结果如下:
{
  "expensiveCount": 3
}(c) 2024 chaojicainiao.com MIT license