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.

MongoClient mongoClient = new MongoClient(
    new MongoClientURI(
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"))
    new Document("$sum", "$quantity"))
    new Document("$avg", "$quantity")))));

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