db.command.aggregate.size
1. Operator Description
Function: Returns the length of the array.
Declaration: db.command.aggregate.size(array)
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | Expression | Required | Can be any expression that resolves to an array. |
3. Sample Code
Suppose the collection shops
contains the following records:
{ "_id": 1, "staff": [ "John", "Middleton", "George" ] }
{ "_id": 2, "staff": [ "Steph", "Jack" ] }
Count the number of employees in each store:
// Sample code in the Cloud Function environment
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('staff')
.aggregate()
.project({
totalStaff: $.size('$staff')
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id": 1, "totalStaff": 3 }
{ "_id": 2, "totalStaff": 2 }