在 SQL 中,您可以执行多个聚合,每个聚合都有自己的条件,在单个查询中,如下所示:
SELECT some_grouping_column,
MAX(some_column WHERE some_flag is true),
COUNT(some_other_column WHERE some_other_flag is false)
FROM some_table
GROUP BY some_grouping_column
在 Mongo 中也可以吗?
是的,你可以做到。我创建了一个场景来计算 stackoverlfow 网站上的每个用户:
我为此使用了多个聚合器:
这是 Json :
[
{
"username": "Stack Overflow User1",
"votes": 5,
"answer": true,
"question": false
},
{
"username": "Stack Overflow User2",
"votes": 10,
"answer": true,
"question": false
},
{
"username": "Stack Overflow User1",
"votes": 5,
"answer": false,
"question": true
},
{
"username": "Stack Overflow User1",
"votes": 8,
"answer": true,
"question": false
},
{
"username": "Stack Overflow User2",
"votes": 7,
"answer": true,
"question": false
}
]
这是具有多个聚合器条件的查询:
db.collection.aggregate([
{
$group: {
_id: "$username",
answer_count: {
$sum: {
$cond: [
"$answer",
1,
0
]
}
},
total_votes: {
$sum: {
$cond: [
"$answer",
"$votes",
0
]
}
},
max_votes: {
$max: {
$cond: [
"$answer",
"$votes",
null
]
}
}
}
}
])
这是它的结果:
[
{
"_id": "Stack Overflow User2",
"answer_count": 2,
"max_votes": 10,
"total_votes": 17
},
{
"_id": "Stack Overflow User1",
"answer_count": 2,
"max_votes": 8,
"total_votes": 13
}
]
这是我尝试过的在线编辑器: https://mongoplayground.net/p/mYjI4L3e8wz