问题
I have a mongodb collection data as per below;I want to group Speciality,Code and Age fields based on EmployeedID( i.e 0001).
{
"_id" : ObjectId("54d0512191a4da7736e9db43"),
"EmployeeID" : "0001",
"Speciality" : "xxx",
"Code" : "P",
"Age" : 8
}
/* 1 */
{
"_id" : ObjectId("54d0512191a4da7736e9db44"),
"EmployeeID" : "0002",
"Speciality" : "yyyyy",
"Code" : "P",
"Age" : 6
}
/* 2 */
{
"_id" : ObjectId("54d0512191a4da7736e9db45"),
"EmployeeID" : "0001",
"Speciality" : "zzz",
"Code" : "P",
"Age" : 5
}
I can already group one field i.e Speciality based on EmployeeID using the way below (push an array). However I am not sure how can I add another fields such as Code and Age into the query?
collection.aggregate([{
$match: {
EmployeeID: '0001'
}
}, {
"$group": {
"_id": "$EmployeeID",
"speciality": {
"$push": "$Speciality"
}
}
}], (function(err, docComp) {
console.log("JSON.stringify" + JSON.stringify(docComp));
}
}));
回答1:
You could either aggregate it as:
collection.aggregate([
{$match:{"EmployeeId":1000}},
{$group:{"_id":"$EmployeeID",
"speciality":{$push:"$Speciality"},
"Code":{$push:"$Code"},
"Age":{$push:"$Age"}}}
])
or,
collection.aggregate([
{$match:{"EmployeeId":1000}},
{$group:{"_id":"$EmployeeID",
"data":{$push:{"Speciality":"$Speciality",
"Code":"$Code",
"Age":"$Age"}}}}
])
来源:https://stackoverflow.com/questions/28292434/mongo-group-and-push-more-than-1-element