Sum all values of same named fields of docs in a collection

前端 未结 1 1805
心在旅途
心在旅途 2021-01-27 00:26

I have a database with the following documents:

{ name: \"John\", a: 20, b: 30, c: 40, d: 50  },     
{ name: \"Rich\", a: 20, b: 30, c: 40, d: 50  },      
{ na         


        
1条回答
  •  后悔当初
    2021-01-27 00:55

    You can take advantage of $objectToArray and $arrayToObject operators to dynamically read your object keys. To get rid of _id and name fields you can $filter by $type.

    db.collection.aggregate([
        {
            $project: {
                _id: 0,
                fields: {
                    $filter: {
                        input: { $objectToArray: "$$ROOT" },
                        cond: { $eq: [ { $type: "$$this.v" }, "double" ] }
                    }
                }
            }
        },
        {
            $unwind: "$fields"
        },
        {
            $group: {
                _id: "$fields.k",
                total: { $sum: "$fields.v" }
            }
        },
        {
            $group: {
                _id: null,
                aggregates: { $push: { k: "$_id", v: "$total" } }
            }
        },
        {
            $replaceRoot: {
                newRoot: { $arrayToObject: "$aggregates" }
            }
        }
    ])
    

    Mongo Playground

    0 讨论(0)
提交回复
热议问题