Mongo aggregation in java: group with multiple fields
<p>I'm trying to perform an aggregation operation using in Java using the mongo-java-driver. I've performed some other find operations, but I'm unable to do the following aggregation correctly in Java:</p>

<pre><code>db.I1.aggregate([
    { "$match": { "ci": 862222} },
    { "$match": { "gi": { "$ne": null } }},
    { "$group": {
        "_id": {
            "ci": "$ci",
            "gi": "$gi",
            "gn": "$gn",
            "si": "$si"
        }
    }},
    { "$group": {
        "_id": {
            "ci": "$_id.ci",
            "gi": "$_id.gi",
            "gn": "$_id.gn"
        },
        "sn": { "$sum": 1 }
    }},
    { "$sort" : { "_id.gi" : 1}}
])
</code></pre>

<p>I've tried several ways and methods to perform that aggregation in Java, but I'm unable to include the group fields <code>"ci", "gi", "gn","si"</code> correctly in the <code>coll.aggregate(asList())</code> method. What I got so far, is the following:</p>

<pre><code>MongoCollection&lt;Document&gt; coll = mongo.getCollection("I1");

Document matchCourse = new Document("$match",
    new Document("ci", Integer.parseInt(courseid)));

Document matchGroupNotNull = new Document("$match",
    new Document("gi", new Document("$ne", null)));

List&lt;Object&gt; list1 = new BasicDBList();
    list1.add(new BasicDBObject("ci", "$ci"));
    list1.add(new BasicDBObject("gi", "$gi"));
    list1.add(new BasicDBObject("gn", "$gn"));
    list1.add(new BasicDBObject("si", "$si"));

Document group1 = new Document(
    "_id", list1).append("count", new Document("$sum", 1));

List&lt;Object&gt; list2 = new BasicDBList();
list2.add(new BasicDBObject("ci", "$_id.ci"));
list2.add(new BasicDBObject("gi", "$_id.gi"));
list2.add(new BasicDBObject("gn", "$_id.gn"));

Document group2 = new Document(
    "_id", list2).append("sn", new Document("$sum", 1));

Document sort = new Document("$sort", 
    new Document("_id.gi", 1));

AggregateIterable&lt;Document&gt; iterable = coll.aggregate(asList(matchCourse,
    matchGroupNotNull, group1, group2, sort));
</code></pre>

<p>I know it's not correct, but I included it to give you an idea of what I am doing. I've googled this in many different ways and read several pages, but I didn't find any solution. The available documentation for MongoDB-Java(<a href="https://docs.mongodb.com/getting-started/java/aggregation/" rel="noreferrer">1</a>, <a href="http://mongodb.github.io/mongo-java-driver/3.2/builders/aggregation/" rel="noreferrer">2</a>) is too short for me and doesn't include this case.</p>

<p>How can I perform that query in Java? Any help would be appreciated. </p>

<p>Thank you very much!!</p>