MongoDB 2.1 Aggregate Framework Sum of Array Elements matching a name

前端 未结 2 1527
别那么骄傲
别那么骄傲 2020-12-05 05:42

This is a question about the best way to add up a series of data in an array where I have to match another element. I\'m trying to use the 2.2 Aggregation framework and it\'

2条回答
  •  爱一瞬间的悲伤
    2020-12-05 05:55

    You can use the aggregation framework to get sales and profit and any other value you may be storing in your key/value pair representation.

    For your example data:

    var pipeline = [
        {
            "$unwind" : "$finance"
        },
        {
            "$group" : {
                "_id" : "$finance.k",
                "numberOf" : {
                    "$sum" : 1
                },
                "total" : {
                    "$sum" : "$finance.v.v"
                }
            }
        }
    ]
    
    R = db.tb.aggregate( pipeline );
    printjson(R);
    {
            "result" : [
                {
                    "_id" : "profit",
                    "numberOf" : 2,
                    "total" : 246246
                },
                {
                    "_id" : "sales",
                    "numberOf" : 2,
                    "total" : 468000
                }
            ],
            "ok" : 1
    }
    

    If you have additional k/v pairs then you can add a match which only passes through k values in ["sales","profit"].

提交回复
热议问题