May 20, 2021 WeChat Mini Program Development Document
Support: Small program 2.7.4, cloud function 0.8.1, Web
The aggregation phase. Specify an existing field as the root node for the output, or you can specify a calculated new field as the root node.
ReplaceRoot is used as follows:
replaceRoot({
newRoot: <表达式>
})
The expression format is as follows:
Format | Description |
---|---|
The name of the field | Specify an existing field as the root node of the output (or error if the field does not exist) |
The object | Calculate a new field and use this new field as the root node |
Let's say we have a schools collection that looks like this:
{
"_id": 1,
"name": "SFLS",
"teachers": {
"chinese": 22,
"math": 18,
"english": 21,
"other": 123
}
}
The following code uses replaceRoot to output the teachers field as the root node:
db.collection('schools')
.aggregate()
.replaceRoot({
newRoot: '$teachers'
})
.end()
The output is as follows:
{
"chinese": 22,
"math": 18,
"english": 21,
"other": 123
}
Let's say we have a roles collection that looks like this:
{ "_id": 1, "first_name": "四郎", "last_name": "黄" }
{ "_id": 2, "first_name": "邦德", "last_name": "马" }
{ "_id": 3, "first_name": "牧之", "last_name": "张" }
The following code uses replaceRoot to first_name between last_name and the following:
const { concat } = db.command.aggregate
db.collection('roles')
.aggregate()
.replaceRoot({
newRoot: {
full_name: concat(['$last_name', '$first_name'])
}
})
.end()
The output is as follows:
{ "full_name": "黄四郎" }
{ "full_name": "马邦德" }
{ "full_name": "张牧之" }