Search code examples
javamongodbquarkusquarkus-panache

Java - Quarkus framework. Panache MongoDB. How to aggregate from code


Using Panache MongoDB, how can you apply the group keyword from code? (Small edit: I want to ask how to apply an aggregation in general, I need group in my specific case, but I couldn't find any aggregation from code)

The documentation doesn't include any example of this, or any complex query for that matter.

So, if I had an entity:

public class myClass extends PanacheMongoEntity{
  String groupId;
  String uuid;
  String otherField;
}

How could I get them split in different collections based on groupId.

For reference, I want to translate this query to in-Java code ('$$ROOT' saving the entirety of the object in every collection, as shown in the MongoDB documentation. This query was generated with MongoBD Compass):

db.getCollection('collection').aggregate(
  [
    {
      $group: {
        _id: '$groupId',
        collection: { $push: '$$ROOT' }
      }
    }
  ],
  { maxTimeMS: 60000, allowDiskUse: true }
);

Solution

  • I learnt how to. You can apply aggregations through the MongoCollection interfact, using Bsons to set the parameters:

    List<Bson> params = new ArrayList<>();
    params.add(
      Aggregates.group(
        "$groupId", new BsonField (
          "itemName", new Document("$push","$$ROOT")
        )
      )
    );
    MyClass.mongoCollection()
      .aggregate( params )
      .toCollection();