MongoDB 中的条件 $sum [英] Conditional $sum in MongoDB
本文介绍了MongoDB 中的条件 $sum的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在mongodb中的集合类似于SQL中的下表:
My collection in mongodb is similar to the following table in SQL:
情绪(公司,情绪)
现在,我需要执行这样的查询:
Now, I need to execute a query like this:
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
我应该怎么做才能在 Mongo 中编写这个查询?我被困在以下查询中:
What should I do to write this query in Mongo? I am stuck at the following query:
db.Sentiments.aggregate(
{ $project: {_id:0, Company:1, Sentiment: 1} },
{ $group: {_id: "$Company", SumPosSenti: {$sum: ? }, SumNegSenti: {$sum: ? } } }
);
推荐答案
正如 Sammaye 所建议的,您需要使用 $cond
聚合投影操作符来做到这一点:
As Sammaye suggested, you need to use the $cond
aggregation projection operator to do this:
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'}
}});
这篇关于MongoDB 中的条件 $sum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文