我只有一个集合雇员: 集合中的数据是
{
"_id" : ObjectId("5b44cb8b44a531b12aa69678"),
"Empid" : 1,
"Empname" : "Raghu",
"Deptid" : "D1",
"Depname" : "IT",
"Salary" : 15000,
"Time" : "8 Hours"
}
{
"_id" : ObjectId("5b44cbda44a531b12aa69679"),
"Empid" : 1,
"Empname" : "Raghu",
"Deptid" : "D2",
"Depname" : "Soft",
"Salary" : 25000,
"Time" : "9 Hours"
}
我希望输出为
{
"Empid" : 1,
"Empname" : "Raghu",
{
"Deptid" : "D1",
"Depname" : "IT",
{
"Salary" : 15000,
"Time" : "8 Hours"
}
}
{
"Deptid" : "D2",
"Depname" : "Soft",
{
"Salary" : 25000,
"Time" : "9 Hours"
}
}
}
答案 0 :(得分:0)
根据上述问题的描述,请尝试在MongoDB shell中执行以下聚合操作。
db.employee.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id: '$Empid',
department: {
$addToSet: {
Deptid: '$Deptid',
Depname: '$Depname',
Salary: '$Salary',
Time: '$Time'
}
},
doc: {
$first: '$$ROOT'
},
}
},
// Stage 2
{
$project: {
Empid: '$_id',
EmpName: '$doc.Empname',
Department: '$department',
_id: 0
}
}
]
);