Mongo aggregation in java: group with multiple fields
Finally I've come to a solution. There were some errors in the question that I posted, as it was the last attempt after reaching some point of desperation, but finally, here is the final solution:
MongoDatabase mongo = // initialize your connection;Document matches = new Document("$match", new Document("gi", new Document("$ne", null)) .append("ci", Integer.parseInt(courseid)));Document firstGroup = new Document("$group", new Document("_id", new Document("ci", "$ci") .append("gi", "$gi") .append("gn", "$gn") .append("si", "$si")) .append("count", new Document("$sum", 1)));Document secondGroup = new Document("$group", new Document("_id", new Document("ci", "$_id.ci") .append("gi", "$_id.gi") .append("gn", "$_id.gn")) .append("ns", new Document("$sum", 1))); Document sort = new Document("$sort", new Document("_id.gi", 1)); List<Document> pipeline = Arrays.asList(matches, firstGroup, secondGroup, sort);AggregateIterable<Document> cursor = mongo.getCollection("I1") .aggregate(pipeline);for(Document doc : cursor) { // do stuff with doc }
Instead of trying to create lists of key-values, I just appended the elements to the documents. Hope it will be useful for somebody!!
This question is quite old but was the top match on google when I searched so if anyone is looking for a solution to this I managed to do it in the following way
Aggregation.group(Fields.fields() .and("field1") .and("field2")) .first("name") .`as`("name") .count().`as`("count")
This will produce the following MDB query:
{ "$group" : { "_id" : { "field1" : "$field1", "field2" : "$field2"}, "name" : { "$first" : "$name"}, "count" : { "$sum" : 1} }