3 回答

TA貢獻1886條經驗 獲得超2個贊
從版本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 }

TA貢獻1794條經驗 獲得超8個贊
解釋上面使用數組語法的片段:
PosSentiment: {$cond: [{$gt: ['$Sentiment', 0]}, '$Sentiment', 0]}
等于:
PosSentiment: {$cond: { if: {$gt: ['$Sentiment', 0]}, then: '$Sentiment', else: 0} }
數組語法總結了長語法 { $cond: [if, then, else] }
- 3 回答
- 0 關注
- 2575 瀏覽
相關問題推薦
添加回答
舉報