Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The SDK database Aggregate calculates the number of records


May 20, 2021 WeChat Mini Program Development Document


Table of contents


Aggregate.count(fieldName: string): Aggregate

Support: Small program 2.7.4, cloud function 0.8.1, Web

The aggregation phase. Calculates the number of records entered into this stage by the previous aggregation stage and outputs a record where the value of the specified field is the number of records.

Parameters

fieldName: string

Returns a value

Aggregate

API description

The form of count is as follows:

count(<string>)

The name of the field that outputs the number of records, cannot be an empty string, cannot begin with $, and cannot contain . Character.

The count stage is equivalent to the operation of group-project:

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

The above outputs a record that contains the count field.

Example

Suppose the collection items have the following records:

{
  _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
}

Find the number of records with a price greater than 50:

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

The results are as follows:

{
  "expensiveCount": 3
}