Search code examples
mongodbaggregation-frameworkmongodb-java

How to write multiple group by id fields in Mongodb java driver


In the below query

{ $group : {
        _id :  { success:'$success', responseCode:'$responseCode', label:'$label'},
        max_timeStamp : { $timeStamp : 1 },
        count_responseCode : { $sum : 1 },
        avg_value : { $sum : "$value" },
        count_success : { $sum : 1 }
    }}

How _id : { success:'$success', responseCode:'$responseCode', label:'$label'}, can be translated to use in java mongodb driver.

I tried

BasicDBList list = new BasicDBList();
list.add(new BasicDBObject("success", "$success"));
list.add(new BasicDBObject("responseCode", "$responseCode"));
list.add(new BasicDBObject("label", "$label"));
AggregationOutput output = collection.aggregate(match, project, group); 

and

Multi-dimension array

String [][] muitiGroupBy = {{"success", "$success"},{"responseCode", "$responseCode"},{"label", "$label"}};

etc..

But i always get like this as result

"_id" : [ { "success" : "$success"} , { "responseCode" : "$responseCode"}]

If I use only one field it works.

DBObject groupFields = new BasicDBObject( "_id", new BasicDBObject("success", "$success"));


Solution

  • We did figure out how. We can achieve by using this.

    Map<String, Object> dbObjIdMap = new HashMap<String, Object>();
    dbObjIdMap.put("success", "$success");
    dbObjIdMap.put("responseCode", "$responseCode");
    dbObjIdMap.put("label", "$label");
    DBObject groupFields = new BasicDBObject( "_id", new BasicDBObject(dbObjIdMap));