我有下面给出的文件
{
"_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"
}
无需对字段进行硬编码,除了按字段分组
db.tbljournal.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id: {
Jid: '$Jid',
JName: '$JName'
},
Article: {
$addToSet: {
"ArtNo": "$ArtNo",
"ArtName": "$ArtName",
"Department": {
"CE": "$CE",
"Dept": "$Dept",
"CEInDate": "$CEInDate",
"DeptInDate": "$DeptInDate"
}
}
}
}
},
{ $sort : {_id:1, ArtNo:-1} }
]
).pretty();
我希望输出如下。
{
"_id" : {
"Jid" : "101",
"JName" : "Artery"
},
"Article" : [
{
"ArtNo" : "2",
"ArtName" : "Blood",
"Department" : {
"CE" : "CE2",
"Dept" : "CopyEditing",
"CEInDate" : "2018-07-10",
"DeptInDate" : "2018-07-10"
}
},
{
"ArtNo" : "1",
"ArtName" : "Nervous",
"Department" : {
"CE" : "CE1",
"Dept" : "Pagination",
"CEInDate" : "2018-07-10",
"DeptInDate" : "2018-07-10"
}
}
]
}