How to groupby multiple fields using the Java MongoDB driver?

I am using mongodb-driver-sync:4.4.1 driver. I want to do a grouping with multiple fields and I want to it to be done using only the new Aggregates Builders. The other answers on this site use BasicDBObject or Document but I don’t want that.

Something like the code below:

Bson groupStage = group(id("$item", "$producer"), sum("totalQuantity", "$quantity"), avg("averageQuantity", "$quantity"));

Didd you find an answer here?

Hi @khat33b ,

Are you reffering to something like below:

/*
 * Requires the MongoDB Java Driver.
 * https://mongodb.github.io/mongo-java-driver
 */

MongoClient mongoClient = new MongoClient(
    new MongoClientURI(
        "mongodb://127.0.0.1:27017/?readPreference=primary&appname=MongoDB+Compass&directConnection=true&ssl=false"
    )
);
MongoDatabase database = mongoClient.getDatabase("db");
MongoCollection<Document> collection = database.getCollection("coll");

FindIterable<Document> result = collection.aggregate(Arrays.asList(new Document("$group", 
    new Document("_id", 
    new Document("item", "$item")
                .append("producer", "$producer"))
            .append("totalQuantity", 
    new Document("$sum", "$quantity"))
            .append("averageQuantity", 
    new Document("$avg", "$quantity")))));

You can use compass aggregation builder to generate the code of your favorite language.

Thanks,
Darshan