本文介绍了Mongo:组合并推送超过1个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mongodb收集数据,如下所示;我想根据EmployeedID(即0001)对Speciality,Code和Age字段进行分组。

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
}

我已经可以使用以下方式将一个字段(即,基于EmployeeID的Specialty)分组(按数组)。但是,我不确定如何在查询中添加其他字段,例如代码和年龄?

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));

    }
}));


推荐答案

您可以将其汇总为:

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"}}}}
])

这篇关于Mongo:组合并推送超过1个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-13 08:21