Mongo Group and sum with two fields

前端 未结 2 413
离开以前
离开以前 2021-01-19 09:13

I have documents like:

{
   \"from\":\"abc@sss.ffffd\",
   \"to\" :\"ssd@dff.dff\",
   \"email\": \"Hi hello\"
}

How can we calculate count o

2条回答
  •  迷失自我
    2021-01-19 09:20

    Since you need to calculate number of emails exchanged between 2 addresses, it would be fair to project a unified between field as following:

    db.a.aggregate([
        { $match: {
            to: { $exists: true },
            from: { $exists: true },
            email: { $exists: true }
        }}, 
        { $project: {
            between: { $cond: { 
                if: { $lte: [ { $strcasecmp: [ "$to", "$from" ] }, 0 ] }, 
                then: [ { $toLower: "$to" }, { $toLower: "$from" } ], 
                else: [ { $toLower: "$from" }, { $toLower: "$to" } ] }
            } 
        }},
        { $group: {
             "_id": "$between",
             "count": { $sum: 1 } 
        }},
        { $sort :{ count: -1 } }
    ])
    

    Unification logic should be quite clear from the example: it is an alphabetically sorted array of both emails. The $match and $toLower parts are optional if you trust your data.

    Documentation for operators used in the example:

    • $match
    • $exists
    • $project
    • $cond
    • $lte
    • $strcasecmp
    • $toLower
    • $group
    • $sum
    • $sort

提交回复
热议问题