Mongo : Group and push more than 1 element

泄露秘密 提交于 2019-12-24 10:49:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!