mongodb - MongoDB 中的条件 $sum

我在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

我应该怎么做才能在 Mongo 中编写这个查询?我被以下查询困住了:

db.Sentiments.aggregate(
{ $project: {_id:0, Company:1, Sentiment: 1} },
{ $group: {_id: "$Company", SumPosSenti: {$sum: ? }, SumNegSenti: {$sum: ? } } }
);

最佳答案

正如 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'}
    }});

https://stackoverflow.com/questions/14102596/

相关文章:

sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点

arrays - MongoDB重命名数组中的数据库字段

mongodb - 在 Mongo 中,如何显示集合的索引?

sql - 为什么 MongoDB 比 SQL DB 快得多的任何详细和具体原因?

mongodb - 在 MongoDB 中创建自定义对象 ID

java - MongoDB 是关系 db + lucene 的有效替代品吗?

MongoDB 查询帮助 - 查询子对象中任何键的值

mongodb - $cond 中存在 $exists 的条件分组

node.js - 如何检查MongoDB native nodejs驱动程序中是否存在集合?

mongodb - 如何在不丢失数据的情况下调整 mongodb 上限集合的大小?