如何在不使用 $facet 的情况下组合两个 MongoDB 聚合管道查询的结果并对组合结果执行另一个聚合查询?

Tiy*_*ose 3 merge aggregation mongodb mongodb-query aggregation-framework

在各种聚合管道阶段之后,我的第一个查询返回以下结果:

{ 
    "group" : "A",
    "count" : 6, 
    "total" : 20
},
{
    "group" : "B",
    "count" : 2,
    "total" : 50
}
Run Code Online (Sandbox Code Playgroud)

在各种聚合管道阶段之后,我的第二个查询返回以下结果:

{
    "group": "A",
    "count": 4,
    "total": 80
},
{
    "group": "C",
    "count": 12,
    "total": 60
}
Run Code Online (Sandbox Code Playgroud)

两个查询都在同一个集合上执行,但根据管道阶段对数据进行不同的分组和转换。

我的两个查询都使用不同的$match条件,具有各种管道阶段,包括$facet,$unwind,$group,$project和运算符,例如$map,$reduce,$zip,$subtract...

db.collection.aggregate([
{ $unwind...},
{ $match....},
{ $facet...},
...
])
Run Code Online (Sandbox Code Playgroud)

当我将$facet查询作为并行查询运行时,会出现以下错误(因为我已经$facet在现有查询中使用了):

$facet is not allowed to be used within a $facet stage
Run Code Online (Sandbox Code Playgroud)

预期输出:

我需要找到每个组的平均值。

为此,我需要组合两个查询的结果并对组合结果执行查询。

我的组合阶段应该是这样的:

{ 
    "group" : "A",
    "count" : 10, 
    "total" : 100 
},
{
    "group" : "B",
    "count" : 2,
    "total" : 50
},
{
    "group": "C",
    "count": 12,
    "total": 60
}
Run Code Online (Sandbox Code Playgroud)

预期的最终结果,每个组的平均值:

{
    "group" : "A",
     "avg" : 10 
},
{
    "group" : "B",
    "avg" : 25
},
{
    "group": "C",
    "avg": 5
}
Run Code Online (Sandbox Code Playgroud)

MongoDB 聚合管道中是否有任何运算符可以在不修改现有查询的情况下实现此目的?

如何实现这个用例?

谢谢!

mic*_*ckl 5

您可以使用$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" ] }
        }
    }
])
Run Code Online (Sandbox Code Playgroud)

蒙戈游乐场

注意:我使用_字符来指示文档来自哪个查询。显然你不需要它,你可以$facet用你自己的替换查询