Aggregate.replaceRoot(object: Object): Aggregate

    聚合阶段。指定一个已有字段作为输出的根节点,也可以指定一个计算出的新字段作为根节点。

    Aggregate

    使用形式如下:

    使用已有字段作为根节点

    假设我们有一个 schools 集合,内容如下:

    1. {
    2. "_id": 1,
    3. "teachers": {
    4. "chinese": 22,
    5. "math": 18,
    6. "english": 21,
    7. "other": 123
    8. }

    下面的代码使用 replaceRoot,把 teachers 字段作为根节点输出:

    1. {
    2. "chinese": 22,
    3. "math": 18,
    4. "other": 123
    5. }

    使用计算出的新字段作为根节点

    假设我们有一个 roles 集合,内容如下:

    下面的代码使用 replaceRoot,把 和 last_name 拼在一起:

    1. const { concat } = db.command.aggregate
    2. db.collection('roles')
    3. .aggregate()
    4. .replaceRoot({
    5. newRoot: {
    6. full_name: concat(['$last_name', '$first_name'])
    7. }
    8. })