Aaf*_*ikh 37 sql mongodb mongodb-query aggregation-framework
我在mongodb中的集合类似于SQL中的下表:
情感(公司,感悟)
现在,我需要执行这样的查询:
SELECT
Company,
SUM(CASE WHEN Sentiment >0 THEN Sentiment ELSE 0 END) AS SumPosSenti,
SUM(CASE WHEN Sentiment <0 THEN Sentiment ELSE 0 END) AS SumNegSenti
FROM Sentiments
GROUP BY Company
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能在Mongo中编写这个查询?我被困在以下查询中:
db.Sentiments.aggregate(
{ $project: {_id:0, Company:1, Sentiment: 1} },
{ $group: {_id: "$Company", SumPosSenti: {$sum: ? }, SumNegSenti: {$sum: ? } } }
);
Run Code Online (Sandbox Code Playgroud)
Joh*_*yHK 50
正如Sammaye建议的那样,您需要使用$cond聚合投影运算符来执行此操作:
db.Sentiments.aggregate(
{ $project: {
_id: 0,
Company: 1,
PosSentiment: {$cond: [{$gt: ['$Sentiment', 0]}, '$Sentiment', 0]},
NegSentiment: {$cond: [{$lt: ['$Sentiment', 0]}, '$Sentiment', 0]}
}},
{ $group: {
_id: "$Company",
SumPosSentiment: {$sum: '$PosSentiment'},
SumNegSentiment: {$sum: '$NegSentiment'}
}});
Run Code Online (Sandbox Code Playgroud)
sty*_*ane 33
从版本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
}
}
}
}}
]
)
Run Code Online (Sandbox Code Playgroud)
如果您尚未迁移您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
]
}
}
}}
]
)
Run Code Online (Sandbox Code Playgroud)
考虑一个带有以下文档的集合Sentiments:
{ "Company": "a", "Sentiment" : 2 }
{ "Company": "a", "Sentiment" : 3 }
{ "Company": "a", "Sentiment" : -1 }
{ "Company": "a", "Sentiment" : -5 }
Run Code Online (Sandbox Code Playgroud)
聚合查询产生:
{ "_id" : "a", "SumPosSenti" : 5, "SumNegSenti" : -6 }
Run Code Online (Sandbox Code Playgroud)
解释上面使用数组语法的片段:
PosSentiment: {$cond: [{$gt: ['$Sentiment', 0]}, '$Sentiment', 0]}
Run Code Online (Sandbox Code Playgroud)
等于:
PosSentiment: {$cond: { if: {$gt: ['$Sentiment', 0]}, then: '$Sentiment', else: 0} }
Run Code Online (Sandbox Code Playgroud)
数组语法将长语法总结为 { $cond: [if, then, else] }