我正在尝试使用$group
对数据进行分组,但没有得到预期的输出。
这是我的代码
https://codesandbox.io/s/lively-tree-hd0fo
app.get("/filter", async (req, res) => {
try {
BlogPostModel.aggregate([
{
$group: {
_id: { empid: "$empid" },
data: {
$addToSet: { attendence: "$attendence", date: "$date", id: "$id" }
}
}
}
]).then(function(re) {
console.log(re); // [ { maxBalance: 98000 } ]
res.send(re);
});
} catch (error) {
console.log(error);
}
});
获取输出
[
{
"_id": {
"empid": "a2"
},
"data": [
{
"attendence": "P",
"date": "2019-07-02T00:00:00.000Z",
"id": "ec8d2107f1ec9c509845232f5aeeadd4"
},
{
"attendence": "A",
"date": "2019-07-01T00:00:00.000Z",
"id": "c91a157c038328d0a9a9d501b2322ee4"
}
]
},
{
"_id": {
"empid": "a1"
},
"data": [
{
"attendence": "A",
"date": "2019-07-03T00:00:00.000Z",
"id": "e85904145b5c104f108a701ab4a7d511"
},
{
"attendence": "P",
"date": "2019-07-02T00:00:00.000Z",
"id": "75f8f4bd1db70519d90e740a89d5b77d"
},
{
"attendence": "P",
"date": "2019-07-01T00:00:00.000Z",
"id": "a1e428379285f56c021f4792e74ed520"
}
]
}
]
预期输出
[
{
"empid": "a2",
"name": "rajat",
"data": [
{
"attendence": "P",
"date": "2019-07-02T00:00:00.000Z",
"id": "ec8d2107f1ec9c509845232f5aeeadd4"
},
{
"attendence": "A",
"date": "2019-07-01T00:00:00.000Z",
"id": "c91a157c038328d0a9a9d501b2322ee4"
}
]
},
{
"empid": "a1",
name:"ravi",
"data": [
{
"attendence": "A",
"date": "2019-07-03T00:00:00.000Z",
"id": "e85904145b5c104f108a701ab4a7d511"
},
{
"attendence": "P",
"date": "2019-07-02T00:00:00.000Z",
"id": "75f8f4bd1db70519d90e740a89d5b77d"
},
{
"attendence": "P",
"date": "2019-07-01T00:00:00.000Z",
"id": "a1e428379285f56c021f4792e74ed520"
}
]
}
]
答案 0 :(得分:0)
BlogPostModel.aggregate(
[
{$group: {_id: '$empid', data: {$addToSet: { attendence: "$attendence", date: "$date", id: "$id" }}}},
{$project: {empid: '$_id', _id: 0, data: 1}}
])