如果我有这样的收藏:

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

但是,如何在一个查询中执行此操作?

最佳答案

您可以汇总如下:

通过$group字段的

  • store,计算subtotal
  • $project字段doc,以在下一次运行期间保持subtotal组完整
    团体。
  • $groupnull并累计 Netty 。

  • 代码:
    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/

    10-08 22:23