从版本3.4开始,我们可以使用
$switch
运算符,在
$group
阶段中进行逻辑条件处理。当然,我们仍然需要使用
$sum
累加器来返回总和。
db.Sentiments.aggregate(
[
{ "$group": {
"_id": "$Company",
"SumPosSenti": {
"$sum": {
"$switch": {
"branches": [
{
"case": { "$gt": [ "$Sentiment", 0 ] },
"then": "$Sentiment"
}
],
"default": 0
}
}
},
"SumNegSenti": {
"$sum": {
"$switch": {
"branches": [
{
"case": { "$lt": [ "$Sentiment", 0 ] },
"then": "$Sentiment"
}
],
"default": 0
}
}
}
}}
]
)
如果您还没有将
mongod
迁移到3.4或更新版本,请注意,此
答案中的
$project
阶段是多余的,因为
$cond
运算符返回数字值,这意味着您可以对文档进行
$group
并将
$sum
应用于
$cond
表达式。这将提高应用程序的性能,特别是对于大型集合。
db.Sentiments.aggregate(
[
{ '$group': {
'_id': '$Company',
'PosSentiment': {
'$sum': {
'$cond': [
{ '$gt': ['$Sentiment', 0]},
'$Sentiment',
0
]
}
},
'NegSentiment': {
'$sum': {
'$cond': [
{ '$lt': ['$Sentiment', 0]},
'$Sentiment',
0
]
}
}
}}
]
)
考虑一个包含以下文档的集合 Sentiments:
{ "Company": "a", "Sentiment" : 2 }
{ "Company": "a", "Sentiment" : 3 }
{ "Company": "a", "Sentiment" : -1 }
{ "Company": "a", "Sentiment" : -5 }
聚合查询产生的结果为:
{ "_id" : "a", "SumPosSenti" : 5, "SumNegSenti" : -6 }
$cond
:http://docs.mongodb.org/manual/reference/aggregation/#conditional-expressions,但这听起来像是对速度和可扩展性查询的破坏,我可以想象这个查询在 SQL 中很慢,在这里处理中等结果集也会很慢。 - SammayeSentiment >0
,然后是Sentiment
,接着是第一个 $sum 中的第一个 $cond 的0
。 - Sammaye