Combine multiple groups in an aggregation in mongodb

前端 未结 2 1710
名媛妹妹
名媛妹妹 2021-01-18 00:22

If I have a collection like this:

{
    \"store\" : \"XYZ\",
    \"total\" : 100
},
{
    \"store\" : \"XYZ\",
    \"total\" : 200
},
{
    \"store\" : \"ABC         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-18 01:11

    You could aggregate as below:

    • $group by the store field, calculate the subtotal.

    • $project a field doc to keep the subtotal group in tact, during the next group.

    • $group by null and accumulate the net total.

    Code:

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

    Output:

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

提交回复
热议问题