mongodb - 通过更改数据视图创建新集合
问题描述
我有带有部门信息的 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"...
}]
}
解决方案
以下查询可以为我们提供预期的输出:
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
}
]
}
推荐阅读
- cryptography - 保护数据的非加密算法
- python - python3 tkinter网格在绘制“表格”时停止
- c# - 如何从第一页中删除页脚模板?
- php - 如何从变量在 PHP 中写入文本文件?
- yocto - SYSTEMD_SERVICE_swupdate 值 swupdate.service 不存在
- jquery - 删除数据后如何显示消息,asp.net core - MVC?
- python - 识别所选表的表行中没有类属性的那些
- python - 将 JSON 数据从 URL 解析到 MySQL
- swift - 使用 PHAsset 无法为 iCloud 照片加载 GIF 和视频
- linq - 尽管有 AsNoTracking,实体仍被跟踪