Mongo Group 和两个字段的总和 [英] Mongo Group and sum with two fields
问题描述
我有如下文件:
{
"from":"abc@sss.ddd",
"to" :"ssd@dff.dff",
"email": "Hi hello"
}
我们如何计算from and to"或to and from"的总和计数?喜欢两个人之间的交流吗?
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}
}
])
推荐答案
由于需要计算在 2个地址之间交换的电子邮件数量,所以投影一个统一的在
字段如下:
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:
这篇关于Mongo Group 和两个字段的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!