如何在Mongodb java驱动程序中按id字段编写多个组

时间:2013-03-22 06:59:37

标签: mongodb aggregation-framework mongodb-java

在以下查询中

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

如何将_id : { success:'$success', responseCode:'$responseCode', label:'$label'},转换为在java mongodb驱动程序中使用。

我试过

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

多维数组

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

等。

但我总是这样结果

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

如果我只使用一个字段就行。

DBObject groupFields = new BasicDBObject(“_ id”,new BasicDBObject(“success”,“$ success”));

3 个答案:

答案 0 :(得分:5)

我们确实弄明白了。我们可以使用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));

答案 1 :(得分:0)

我可以通过这段代码实现这一点(grails代码和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()

答案 2 :(得分:0)

我也有类似的需求,在多次尝试将聚合操作转换为Java客户端可以处理的操作失败之后,2013年的titogeo的回答将我引向了正确的方向。这就是我用的:

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

我完全得到了匹配结果所需的信息:

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