summation of two columns in Aggregate Method

前端 未结 2 922
醉酒成梦
醉酒成梦 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:47

    Use $facet pipeline stage to process multiple aggregation pipelines within a single stage on the same set of input documents. In your case you need to aggregate the counts separately then join the two results and calculate the final aggregates.

    This can be demonstrated by running the following pipeline:

    db.collection.aggregate([
        { "$match": { "userid": "123" } },
        {
            "$facet": {
                "groupByPage": [
                    { "$unwind": "$page" },
                    { 
                        "$group": {
                            "_id": "$page",
                            "count": { "$sum": 1 }
                        }
                    }
                ],   
                "groupByNewPage": [
                    { "$unwind": "$newpage" },
                    { 
                        "$group": {
                            "_id": "$newpage",
                            "count": { "$sum": 1 }
                        }
                    }
                ]
            }
        },
        { 
            "$project": {
                "pages": {
                    "$concatArrays": ["$groupByPage", "$groupByNewPage"]
                }
            }
        },
        { "$unwind": "$pages" },
        { 
            "$group": {
                "_id": "$pages._id",
                "count": { "$sum": "$pages.count" }
            }
        },
        { "$sort": { "count": -1 } }
    ], function(error, data){
        if (error) {
            console.log(error);
        } else {
            console.log(data);
        }
    )
    

提交回复
热议问题