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

时光毁灭记忆、已成空白 提交于 2019-12-05 11:41:01

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

I had a similar need and titogeo's answer from 2013 led me in the right direction after many failed attempts to translate my aggregation operation into something the Java client could handle. This is what I used:

MongoCollection<Document> myCollection = myDB.getCollection("myCollection");

Map<String, Object> multiIdMap = new HashMap<String, Object>();
multiIdMap.put("groupField1", "$groupField1");
multiIdMap.put("groupField2", "$groupField2");

Document groupFields = new Document(multiIdMap);
AggregateIterable<Document> aggregate = myCollection.aggregate(Arrays.asList(
        Aggregates.group(groupFields,
                Accumulators.last("lastDate", "$dateCreated"),
                Accumulators.last("lastNumAvail", "$availableUnits")
                )
        ));

I got back exactly what I needed to match the result from this:

db.myCollection.aggregate([
            {"$group":{ "_id":{
                groupField1: "$groupField1", 
                groupField2: "$groupField2"}, 
                lastDate: 
                    {"$last":"$dateCreated"}, 
                lastNumAvail: 
                    {"$last":"$availableUnits"}
                }
               }                
            ]);

I could achieve this through this code (grails code and mongo-java-driver-3.2):

DBObject groupFields = new BasicDBObject()
groupFields.put('success', "\$success")
groupFields.put('responseCode', "\$responseCode")
groupFields.put('label', "\$label")
def result = collection.aggregate(Arrays.asList(Aggregates.group(groupFields, []))).iterator()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!