Aggregate.replaceRoot(object: Object): Aggregate
聚合阶段。指定一个已有字段作为输出的根节点,也可以指定一个计算出的新字段作为根节点。
Aggregate
使用形式如下:
使用已有字段作为根节点
假设我们有一个 schools
集合,内容如下:
{
"_id": 1,
"teachers": {
"chinese": 22,
"math": 18,
"english": 21,
"other": 123
}
下面的代码使用 replaceRoot
,把 teachers
字段作为根节点输出:
{
"chinese": 22,
"math": 18,
"other": 123
}
使用计算出的新字段作为根节点
假设我们有一个 roles
集合,内容如下:
下面的代码使用 replaceRoot
,把 和 last_name
拼在一起:
const { concat } = db.command.aggregate
db.collection('roles')
.aggregate()
.replaceRoot({
newRoot: {
full_name: concat(['$last_name', '$first_name'])
}
})