summation of two columns in Aggregate Method

前端 未结 2 897
醉酒成梦
醉酒成梦 2021-01-22 00:17

I am using mongodb Aggregate query. My db is like this:

{
  \"_id\" : ObjectId(\"5a81636f017e441d609283cc\"),
  \"userid\": \"123\",
  page : \'A\',
  newpage: \         


        
2条回答
  •  长发绾君心
    2021-01-22 00:41

    There you go:

    db.Collection.aggregate([
        {$match:{ "userid":"123"}}, // filter out what's not of interest
        {$facet: { // process two stages in parallel --> this will give us a single result document with the following two fields
            "newpage": [ // "newpage" holding the ids and sums per "newpage" field
                {$group:{"_id":"$newpage", "count":{"$sum":1}}}
            ],
            "page": [ // and "page" holding the ids and sums per "page" field
                {$group:{"_id":"$page", "count":{"$sum":1}}}
            ]
        }},
        {$project: {x:{$concatArrays:["$newpage", "$page"]}}}, // merge the two arrays into one
        {$unwind: "$x"}, // flatten the single result document into multiple ones so we do not need to $reduce but can nicely $group
        {$group: {_id: "$x._id", "count": {$sum: "$x.count"}}} // perform the final grouping/counting,
        {$sort: {count: -1}} // well, the sort according to your question
    ]);
    

提交回复
热议问题