首页 > 解决方案 > 通过更改数据视图创建新集合

问题描述

我有带有部门信息的 mongo Employee 集合作为嵌套文档。

例子:

{
    "_id": 7934,
    "ename": "MILLER",
    "job": "CLERK",
    "mgr": "7782",
    "hiredate": ISODate("1982-01-22T18:30:00Z"),
    "sal": 1300,
    "department": {
        "deptno": 10,
        "dname": "ACCOUNTING",
        "loc": "NEW YORK"
    }
}

现在,我必须通过使用 Employee 集合来创建一个新集合,以将部门信息作为根,并包含该部门的一组员工。

例子:

{
    "_id": 10,
    "deptno": 10,
    "dname": "ACCOUNTING",
    "loc": "NEW YORK",
    "employees": [{
        "ename": "MILLER",
        "job": "CLERK",
        "mgr": "7782",
        "hiredate": ISODate("1982-01-22T18:30:00Z"),
        "sal": 1300
    }, {
        "ename": "JOHN"...
    }]
}

标签: mongodbaggregation-framework

解决方案


以下查询可以为我们提供预期的输出:

db.collection.aggregate([
    {
        $group:{
            "_id":"$department.deptno",
            "department":{
                $first:"$department"
            },
            "employees":{
                $push:"$$ROOT"
            }
        }
    },
    {
        $replaceRoot:{
            "newRoot":{
                $mergeObjects:[
                    "$department",
                    {
                        "employees":"$employees"
                    }
                ]
            }
        }
    },
    {
        $project:{
            "employees.department":0
        }
    },
    {
        $out:"department"
    }
]).pretty()

数据集:

{
    "_id" : 7934,
    "ename" : "MILLER",
    "job" : "CLERK",
    "mgr" : "7782",
    "hiredate" : ISODate("1982-01-22T18:30:00Z"),
    "sal" : 1300,
    "department" : {
        "deptno" : 10,
        "dname" : "ACCOUNTING",
        "loc" : "NEW YORK"
    }
}
{
    "_id" : 7935,
    "ename" : "MECHANIC",
    "job" : "CEO",
    "mgr" : "7700",
    "hiredate" : ISODate("1982-01-22T18:30:00Z"),
    "sal" : 9999999999999,
    "department" : {
        "deptno" : 10,
        "dname" : "ACCOUNTING",
        "loc" : "NEW YORK"
    }
}

收藏:部门

{
    "deptno" : 10,
    "dname" : "ACCOUNTING",
    "loc" : "NEW YORK",
    "employees" : [
        {
            "_id" : 7934,
            "ename" : "MILLER",
            "job" : "CLERK",
            "mgr" : "7782",
            "hiredate" : ISODate("1982-01-22T18:30:00Z"),
            "sal" : 1300
        },
        {
            "_id" : 7935,
            "ename" : "MECHANIC",
            "job" : "CEO",
            "mgr" : "7700",
            "hiredate" : ISODate("1982-01-22T18:30:00Z"),
            "sal" : 9999999999999
        }
    ]
}

推荐阅读