db.command.aggregate.push
1. Operator Description
Function: In the group
stage, returns an array composed of the expression-specified column and its corresponding values within a group.
Declaration: db.command.aggregate.push({ <fieldName1>: <specifiedField1>, <fieldName2>: <specifiedField2>, ... })
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | Object | Yes | The object key-value is any aggregation expression. |
3. Sample Code
Suppose the collection students
contains the following records:
{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }
Using the push
operator, for all records in different groups (group
), it aggregates all data and places it into a new field, further structuring and adding semantic meaning to the data.
// 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('students')
.aggregate()
.group({
_id: '$group',
students: $.push({
name: '$name',
score: '$score'
})
})
.end()
console.log(res.data)
}
The output is as follows:
{ "_id": "b", "students": [{ "name": "stu3", "score": 80 }, { "name": "stu4", "score": 100 }] }
{ "_id": "a", "students": [{ "name": "stu1", "score": 84 }, { "name": "stu2", "score": 96 }] }