Skip to main content

Aggregate.replaceRoot

1. Interface Description

Function: Aggregation stage. Specifies an existing field as the root node of the output, or specifies a newly computed field as the root node.

Syntax: replaceRoot({ newRoot: <expression> })

2. Input Parameters

ParameterTypeRequiredDescription
newRootAggregate or ObjectYesThe two formats are detailed below

The expression format is as follows:

FormatDescription
<field name>Specify an existing field as the root node of the output (an error will be reported if the field does not exist)
<object>Compute a new field and use this new field as the root node

3. Response

ParameterTypeRequiredDescription
-AggregateYesAggregation object

4. Sample Code

Using an Existing Field as the Root Node

Suppose we have a schools collection with the following content:

{
"_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:

const tcb = require("@cloudbase/node-sdk");
const app = tcb.init({
env: "xxx",
});

const db = app.database();
const { gt, sum } = db.command.aggregate;

exports.main = async (event, context) => {
const res = await db
.collection("schools")
.aggregate()
.replaceRoot({
newRoot: "$teachers",
})
.end();
console.log(res.data);
};

The output is as follows:

{
"chinese": 22,
"math": 18,
"english": 21,
"other": 123
}

Using a Computed New Field as the Root Node

Suppose we have a roles collection with the following content:

{ "_id": 1, "first_name": "Silang", "last_name": "Huang" }
{ "_id": 2, "first_name": "Bond", "last_name": "Ma" }
{ "_id": 3, "first_name": "Muzhi", "last_name": "Zhang" }

The following code uses replaceRoot to concatenate first_name and last_name:

const tcb = require("@cloudbase/node-sdk");
const app = tcb.init({
env: "xxx",
});

const db = app.database();
const { gt, sum, concat } = db.command.aggregate;

exports.main = async (event, context) => {
const res = await db
.collection("roles")
.aggregate()
.replaceRoot({
newRoot: {
full_name: concat(["$last_name", "$first_name"]),
},
})
.end();
console.log(res.data);
};

The output is as follows:

{ "full_name": "Huang Silang" }
{ "full_name": "Ma Bangde" }
{ "full_name": "Zhang Muzhi" }