在mongo中不止一次分组

时间:2014-12-10 16:17:42

标签: mongodb mongodb-java

我是mongo db的新手,

我在mysql中有以下代码:

SELECT sum(Sentiment)/count(*), sum(Intensity)/count(*), count(*) FROM omid.tweet 

我需要将其转换为mongodb:

但是我真的很混淆了多个列,例如我有:

// Now the $group operation
    DBObject groupFields = new BasicDBObject( "_id", "$?????");
    groupFields.put("average", new BasicDBObject( "$avg", "$intensity"));
    DBObject group = new BasicDBObject("$group", groupFields);

但正如你所看到的那样,我不知道如何分享内容以及如何获得平均情绪。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您不需要按照您想要实现的目标进行多次分组。您可以使用$avg$sumaggregation framework聚合运算符:

db.collection.aggregate(
   [
     {
       $group:
         {
           _id: null,
           avgSentiment: { $avg: "$sentiment" },
           avgIntensity: { $avg: "$intensity" },
           count: { $sum: 1 }
         }
     }
   ]
)

未经测试 Java等效项:

// $group in Java
DBObject groupFields = new BasicDBObject( "_id", null);
groupFields.put("avgSentiment", new BasicDBObject( "$avg", "$sentiment"));
groupFields.put("avgIntensity", new BasicDBObject( "$avg", "$intensity"));
groupFields.put("count", new BasicDBObject( "$sum", 1));
DBObject group = new BasicDBObject("$group", groupFields);

// Run aggregation
List<DBObject> pipeline = Arrays.asList(group);
AggregationOutput output = collection.aggregate(pipeline);