dim*_*wc3 5 database mongodb nosql aggregation-framework
我有收款账户:
{
"_id": ObjectId("571a0e145d29024733793cfe"),
"name": "Cash",
"user": ObjectId("571a0e145d29024733793cfc")
}
Run Code Online (Sandbox Code Playgroud)
和交易。交易可以有不同的字段:
{
"_id": ObjectId("571a0e145d29024733793d06"),
"amount": 100,
"type": "earned",
"account": ObjectId("571a0e145d29024733793cfe"),
"user": ObjectId("571a0e145d29024733793cfc"),
},
{
"_id": ObjectId("571a0e145d29024733793d04"),
"amount": 300,
"type": "spent",
"account": ObjectId("571a0e145d29024733793cfe"),
"user": ObjectId("571a0e145d29024733793cfc")
},
{
"_id": ObjectId("571a0e145d29024733793d07"),
"amount": 100,
"type": "transfer",
"sourceAccount": ObjectId("571a0e145d29024733793cfd"),
"destinationAccount": ObjectId("571a0e145d29024733793cfe"),
"user": ObjectId("571a0e145d29024733793cfc"),
}
Run Code Online (Sandbox Code Playgroud)
我想按每个帐户进行统计分组。我写了一个聚合框架查询到数据库:
db.transactions.aggregate([
{ $match: { user: user._id } },
{
$group: {
_id: '$account',
earned: {
$sum: {
$cond: [{ $eq: ['$type', 'earned'] }, '$amount', 0]
}
},
spent: {
$sum: {
$cond: [{ $eq: ['$type', 'spent'] }, '$amount', 0]
}
},
deposits: {
$sum: {
$cond: [{ $eq: ['$type', 'transfer'] }, '$amount', 0]
}
},
withdrawal: {
$sum: {
$cond: [{ $eq: ['$type', 'transfer'] }, '$amount', 0]
}
},
maxEarned: {
$max: {
$cond: [{ $eq: ['$type', 'earned'] }, '$amount', 0]
}
},
maxSpent: {
$max: {
$cond: [{ $eq: ['$type', 'spent'] }, '$amount', 0]
}
},
count: { $sum: 1 }
}
}
]);
Run Code Online (Sandbox Code Playgroud)
但它不能正常工作。它仅适用于具有现场帐户的交易。我想按字段帐户或 sourceAccount 或 destinationAccount 分组。
我还尝试在“_id”字段中写入:
_id: { account: '$account', sourceAccount: '$sourceAccount', destinationAccount: '$destinationAccount' }
Run Code Online (Sandbox Code Playgroud)
或者
_id: {$or: ['$account', '$sourceAccount', '$destinationAccount']}
Run Code Online (Sandbox Code Playgroud)
或者
_id: {$in: ['$account', '$sourceAccount', '$destinationAccount']}
Run Code Online (Sandbox Code Playgroud)
但它使错误的组或不起作用。
如何从不同的领域分组?
使用$cond运算符作为_id表达式,根据您指定的条件按键计算分组。该$cond运算符使用比较运算符$gt来计算布尔表达式,该表达式确定该字段是否存在并使用此比较顺序。因此,您可以重组管道,如下例所示:
db.transactions.aggregate([
{
"$group": {
"_id": {
"$cond": [
{ "$gt": [ "$account", null ] },
"$account",
{
"$cond": [
{ "$gt": [ "$sourceAccount", null ] },
"$sourceAccount",
"$destinationAccount"
]
}
]
},
"count": { "$sum": 1 }
}
}
])
Run Code Online (Sandbox Code Playgroud)
样本输出
{ "_id" : ObjectId("571a0e145d29024733793cfd"), "count" : 1 }
{ "_id" : ObjectId("571a0e145d29024733793cfe"), "count" : 2 }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3477 次 |
| 最近记录: |