我是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);
但正如你所看到的那样,我不知道如何分享内容以及如何获得平均情绪。有人可以帮忙吗?
答案 0 :(得分:2)
您不需要按照您想要实现的目标进行多次分组。您可以使用$avg
的$sum
和aggregation 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);