HMdeveloper
HMdeveloper

Reputation: 2874

grouping more than once in mongo

I am new to mongo db,

I have a following code in mysql:

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

and I need to convert it to mongodb:

but I am really confused with group bying more than one column for example I have :

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

but as you can see I do not know to group by on what and also how to get average for sentiment as well. Can anyone help?

Upvotes: 1

Views: 125

Answers (1)

Anand Jayabalan
Anand Jayabalan

Reputation: 12904

You do not need to group by more than once for what you are trying to achieve. You can use the $avg and $sum aggregation operators of the aggregation framework:

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

Untested Java equivalent:

// $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);

Upvotes: 2

Related Questions