gpt4 book ai didi

javascript - 蒙戈 : Group and push more than 1 element

转载 作者:行者123 更新时间:2023-11-28 07:38:50 27 4
gpt4 key购买 nike

我有一个 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 的专业(推送数组)。但是我不确定如何在查询中添加其他字段,例如代码和年龄?

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

关于javascript - 蒙戈 : Group and push more than 1 element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28292434/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com