SDK數(shù)據(jù)庫 Aggregate·計(jì)算記錄數(shù)

2022-05-12 16:46 更新

Aggregate.count(fieldName: string): Aggregate

支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web

聚合階段。計(jì)算上一聚合階段輸入到本階段的記錄數(shù),輸出一個(gè)記錄,其中指定字段的值為記錄數(shù)。

參數(shù)

fieldName: string

返回值

Aggregate

API 說明

count 的形式如下:

count(<string>)

<string> 是輸出記錄數(shù)的字段的名字,不能是空字符串,不能以 $ 開頭,不能包含 . 字符。

count 階段等同于 group + project 的操作:

const $ = db.command.aggregate
db.collection('items').aggregate()
  .group({
    _id: null,
    count: $.sum(1),
  })
  .project({
    _id: 0,
  })
  .end()

上述操作會(huì)輸出一個(gè)包含 count 字段的記錄。

示例

假設(shè)集合 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
}

找出價(jià)格大于 50 的記錄數(shù):

const $ = db.command.aggregate
db.collection('items').aggregate()
  .match({
    price: $.gt(50)
  })
  .count('expensiveCount')
  .end()

返回結(jié)果如下:

{
  "expensiveCount": 3
}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)