Mongo:分组并推送超过1个元素

时间:2015-02-03 06:08:41

标签: javascript mongodb aggregation-framework

我有一个mongodb收集数据,如下所示;我想根据EmployeedID(即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
}

我已经可以使用以下方式将一个字段组合,即基于EmployeeID的Specialty(推送数组)。但是我不知道如何在查询中添加其他字段,如Code和Age?

collection.aggregate([{
    $match: {
        EmployeeID: '0001'
    }
}, {
    "$group": {
        "_id": "$EmployeeID",
        "speciality": {
            "$push": "$Speciality"
        }
    }
}], (function(err, docComp) {

      console.log("JSON.stringify" + JSON.stringify(docComp));

    }
}));

1 个答案:

答案 0 :(得分:0)

您可以将其汇总为:

collection.aggregate([
{$match:{"EmployeeId":1000}},
{$group:{"_id":"$EmployeeID",
            "speciality":{$push:"$Speciality"},
            "Code":{$push:"$Code"},
            "Age":{$push:"$Age"}}}
])

,或者

collection.aggregate([
{$match:{"EmployeeId":1000}},
{$group:{"_id":"$EmployeeID",
            "data":{$push:{"Speciality":"$Speciality",
                           "Code":"$Code",
                           "Age":"$Age"}}}}
])