Javascript 如何在MongoDB中同时使用匹配和求和?
我有字段,Javascript 如何在MongoDB中同时使用匹配和求和?,javascript,mongodb,mongodb-query,aggregation-framework,Javascript,Mongodb,Mongodb Query,Aggregation Framework,我有字段,id,group\u id,revenue和account。我想做一个聚合,其中收入按id分组,与特定的组id匹配并汇总。但是将有两个总和,一个是科目为空,另一个是科目不为空。我该怎么做?这是我迄今为止一直在尝试的 res = await col.aggregate([ { $match: { group_id: "ABC" } }, { $group: { _id: "$id", account: { $first:
id
,group\u id
,revenue
和account
。我想做一个聚合,其中收入按id
分组,与特定的组id
匹配并汇总。但是将有两个总和,一个是科目
为空,另一个是科目
不为空。我该怎么做?这是我迄今为止一直在尝试的
res = await col.aggregate([
{ $match: { group_id: "ABC" } },
{ $group: {
_id: "$id",
account: { $first: '$account' },
total_revenue: { $sum: "$revenue" }, //should be for non-empty account
total_gl: { $sum: "$revenue" } // should be for empty account
} }
])
演示-
用于获取与数据分离的数据
db.collection.aggregate([
{
$match: {
group_id: "ABC"
}
},
{
"$group": {
_id: "$id",
group_id: {
$first: "$group_id"
},
account: {
$first: "$account"
},
revenue: {
"$push": {
"revenue": "$revenue",
"account": "$account"
}
}
}
},
{
"$project": {
_id: 0,
group_id: 1,
account: 1,
total_revenue: {
$filter: {
input: "$revenue",
as: "item",
cond: {
$ne: [
{
$type: "$$item.account"
},
"missing"
]
}
}
},
total_gl: {
$filter: {
input: "$revenue",
as: "item",
cond: {
$eq: [
{
$type: "$$item.account"
},
"missing"
]
}
}
}
}
},
{
"$project": {
group_id: 1,
account: 1,
total_revenue: {
$sum: "$total_revenue.revenue"
},
total_gl: {
$sum: "$total_gl.revenue"
}
}
}
])