I have documents like:
{
\"from\":\"abc@sss.ffffd\",
\"to\" :\"ssd@dff.dff\",
\"email\": \"Hi hello\"
}
How can we calculate count o
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: