mongodb - 在mongodb的一个聚合中组合多个组

标签 mongodb aggregation-framework

如果我有这样的收藏:

{
    "store" : "XYZ",
    "total" : 100
},
{
    "store" : "XYZ",
    "total" : 200
},
{
    "store" : "ABC",
    "total" : 300
},
{
    "store" : "ABC",
    "total" : 400
}

我可以通过聚合得到集合中订单的$sum:

db.invoices.aggregate([{$group: { _id: null, total: { $sum: "$total"}}}])

{
    "result": [{
            "_id": null,
            "total": 1000
        }
    ],
    "ok": 1
}

我可以得到按商店分组的订单的$sum:

db.invoices.aggregate([{$group: { _id: "$store", total: { $sum: "$total"}}}])

{
    "result": [{
            "_id": "ABC",
            "total": 700
        }, {
            "_id": "XYZ",
            "total": 300
        }
    ],
    "ok": 1
}

但是我怎样才能在一个查询中做到这一点呢?

最佳答案

你可以如下聚合:

  • $groupstore字段,计算出subtotal

  • $project 字段 doc 以保持 subtotal 组在下一个 组。

  • $group by null 并累计净总数。

代码:

db.invoices.aggregate([{
            $group: {
                "_id": "$store",
                "subtotal": {
                    $sum: "$total"
                }
            }
        }, {
            $project: {
                "doc": {
                    "_id": "$_id",
                    "total": "$subtotal"
                }
            }
        }, {
            $group: {
                "_id": null,
                "total": {
                    $sum: "$doc.total"
                },
                "result": {
                    $push: "$doc"
                }
            }
        }, {
            $project: {
                "result": 1,
                "_id": 0,
                "total": 1
            }
        }
    ])

输出:

{
    "total": 1000,
    "result": [{
            "_id": "ABC",
            "total": 700
        }, {
            "_id": "XYZ",
            "total": 300
        }
    ]
}

关于mongodb - 在mongodb的一个聚合中组合多个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420631/

相关文章:

mongodb - 使用 mongodb 搜索多个集合

arrays - 仅查询嵌套数组中的数字

java - MongoDB Java 驱动程序聚合框架使用 $match 和 $text $search 但首先需要 $project

node.js - 如何无限填充 mongoDB 模型?

java - 在 Java MongoDb 中,如何将特定字段的值保存在 ArrayList 中?

java - MongoDB Java 使用多个过滤器并获得最后一个

arrays - 数组长度和缺失字段的mongoDB总和

javascript - 使用 mongoose 的 Mongo 自定义排序策略

c# - 将 Microsoft SQL 数据库迁移/转换为 MongoDB 数据库的最佳方法?

node.js - 您如何播种 mongodb 数据库,以便 Keystone 5 CMS 识别多对多关系?