我的第一个查询在各个聚合管道阶段之后返回以下结果:
{
"group" : "A",
"count" : 6,
"total" : 20
},
{
"group" : "B",
"count" : 2,
"total" : 50
}
我的第二个查询在各个聚合管道阶段之后返回以下结果:
{
"group": "A",
"count": 4,
"total": 80
},
{
"group": "C",
"count": 12,
"total": 60
}
Both the queries are performed on the same collection, but groups and transforms the data differently based on the pipeline stages.
Both of my queries use different
$match
conditions, have various pipeline stages including$facet,$unwind,$group,$project
and operators like$map,$reduce,$zip,$subtract
...
db.collection.aggregate([
{ $unwind...},
{ $match....},
{ $facet...},
...
])
当我使用 $facet
将查询作为并行查询运行时,会出现以下错误(因为我已经在现有查询中使用了 $facet
):
$facet is not allowed to be used within a $facet stage
预期输出:
I need to find the average value for each of the group.
为此,我需要合并两个查询的结果并对合并的结果执行查询。
我的组合阶段应该是这样的:
{
"group" : "A",
"count" : 10,
"total" : 100
},
{
"group" : "B",
"count" : 2,
"total" : 50
},
{
"group": "C",
"count": 12,
"total": 60
}
每组平均预期的最终结果:
{
"group" : "A",
"avg" : 10
},
{
"group" : "B",
"avg" : 25
},
{
"group": "C",
"avg": 5
}
MongoDB 聚合管道中是否有可用的运算符来实现此目的而无需修改我现有的查询?
如何实现这个用例?
谢谢!
最佳答案
您可以使用 $facet 单独运行查询然后使用下面的变换到 $group
通过 group
组合结果并计算平均值:
db.collection.aggregate([
{
$facet: {
first: [ { $match: { "_": true } } ], // your first query
second: [ { $match: { "_": false } } ], // your second query
}
},
{
$project: {
all: {
$concatArrays: [ "$first", "$second" ]
}
}
},
{
$unwind: "$all"
},
{
$group: {
_id: "$all.group",
count: { $sum: "$all.count" },
total: { $sum: "$all.total" },
}
},
{
$project: {
_id: 0,
group: "$_id",
count: 1,
total: 1,
avg: { $divide: [ "$total", "$count" ] }
}
}
])
注意:我使用 _
字符来指示文档来自哪个查询。显然你不需要它,你可以用你自己的替换 $facet
查询
关于mongodb - 如何在不使用 $facet 的情况下组合两个 MongoDB 聚合管道查询的结果并对组合结果执行另一个聚合查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62880750/