Aggregate.count
1. Interface Description
Function: Aggregation stage. Counts the number of input records and outputs a record with a specified field set to the count value. The count
stage is equivalent to the operation of group
+ project
.
declaration: count(string)
2. Input Parameters
Parameter | Type | Required | Description |
---|---|---|---|
- | expression | Required | string is the field name for the output record count. It cannot be an empty string, must not start with $ , and must not contain the . character. |
3. Response
Parameter | Type | Required | Description |
---|---|---|---|
- | Aggregate | Yes | Aggregation object |
4. Sample Code
Suppose the collection items
contains 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 where the price is greater than 50:
const tcb = require("@cloudbase/node-sdk");
const app = tcb.init({
env: "xxx",
});
const db = app.database();
const $ = db.command.aggregate;
const _ = db.command;
exports.main = async (event, context) => {
const res = await db
.collection("items")
.aggregate()
.match({
price: _.gt(50),
})
.count("expensiveCount")
.end();
console.log(res.data);
};
The returned result is as follows:
{
"expensiveCount": 3
}