我正在使用汇总将一些数据分组。我想填充“ _id”字段。
让我们说我有费用表。其中已提交“金额”,“类型”,“ created_at”,“ created_by”。现在我想按类型将类型分组,我将提供参数并显示每个用户按类型花费的金额。例如->
{
"_id": "A",
"user_group": [
{
"user": "user1",
"data": 6600
}
],
"amount": 6600
},
{
"_id": "B",
"user_group": [
{
"user": "user1",
"data": 21535.1
},
{
"user": "user2",
"data": 500
}
],
"amount": 22035.1
},
我的代码->
Expense.aggregate([
{
$match: {
$and:
[
{ type: { $in: req.query.types} },
//{ created_at: Date }
]
}
},
{
$group: {
"_id": {
type: "$type",
user: "$created_by"
},
"amount": { "$sum": "$amount" },
"data": { $push: "$$ROOT" }
}
}, {
$group: {
_id: "$_id.type",
user_group: {
$push: {
user: "$_id.user",
data: { "$sum": "$data.amount" },
username: "$user"
}
},
amount: { "$sum": "$amount" },
}
},
], function (err, data) {
if (err) {
console.log("Error: ", err);
res.json({
success: false,
});
} else {
res.json({
success: true,
data: data
});
}
});
使用此代码,我无法从用户表中获取用户名。我得到的数据是->
{
"_id": "A",
"user_group": [
{
"user": "5b782c3010a1683090429771",
"data": 6600
}
],
"amount": 6600
},
{
"_id": "B",
"user_group": [
{
"user": "5be6d50e1ee4e926dc5ba6f0",
"data": 21535.1
},
{
"user": "5b782c3010a1683090429771",
"data": 500
}
],
"amount": 22035.1
},
我要填充用户字段。我怎样才能做到这一点? 提前谢谢。