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

标签 mongodb merge mongodb-query aggregation-framework aggregation

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

{ 
    "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" ] }
        }
    }
])

Mongo Playground

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

关于mongodb - 如何在不使用 $facet 的情况下组合两个 MongoDB 聚合管道查询的结果并对组合结果执行另一个聚合查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62880750/

相关文章:

node.js - MongoDB:$lookup 数组后的 $sum

javascript - 尝试使用 'group ' 和 find() 在 Mongoose 中执行 '$expr' 时出错

git - 如何解决 TortoiseGit 中的已删除 merge 冲突?

mongodb - Mongo查询子文档的多个字段

MongoDB聚合从嵌套数组中获取最后一个元素的字段

Python如何合并两个csv文件

javascript - 从数组的数组中的对象获取值

mongodb - 无法使用 Monk/Mongo 按名称找到用户

node.js - 如何使用多个条件更新集合文档

variables - LESS 合并变量名并获取值