Mongo Group和两个字段的和 [英] Mongo Group and sum with two fields
问题描述
我有类似的文件:
{
"from":"abc@sss.ddd",
"to" :"ssd@dff.dff",
"email": "Hi hello"
}
我们如何计算从和到"或从和到"的总数? 就像两个人之间的交流很重要吗?
How can we calculate count of sum "from and to" or "to and from"? Like communication counts between two people?
我能够计算单向总和.我想双向求和.
I am able to calculate one way sum. I want to have sum both ways.
db.test.aggregate([
{ $group: {
"_id":{ "from": "$from", "to":"$to"},
"count":{$sum:1}
}
},
{
"$sort" :{"count":-1}
}
])
推荐答案
由于您需要计算在两个地址之间交换的电子邮件数量,因此将一个统一的between
字段投影为以下:
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 } }
])
从示例中可以很清楚地看出统一逻辑:这是两个电子邮件的按字母顺序排序的数组.如果您信任自己的数据,则$match
和$toLower
部分是可选的.
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
这篇关于Mongo Group和两个字段的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!