public List<Document> queryMoviesByYear(String year) {
MovieAggregationService service = new MovieAggregationService(client.getDatabase("sample_mflix").getCollection("movies"));
return service.queryMoviesByYear(year);
}
class MovieAggregationService {
private final MongoCollection<Document> collection;
public MovieAggregationService(MongoCollection<Document> collection) {
this.collection = collection;
}
public List<Document> queryMoviesByYear(String year) {
return collection.aggregate(createPipeline(year)).into(new ArrayList<>());
}
private List<Bson> createPipeline(String year) {
return List.of(
Aggregates.match(Filters.eq("year", year)),
Aggregates.group("newField",
Accumulators.avg("test", "$year"),
Accumulators.sum("test2", "$year"),
Accumulators.bottom("field", Sorts.ascending("year"), "$year")
),
Aggregates.project(Projections.fields(Projections.include("year", "plot"))),
Aggregates.sort(Sorts.orderBy(Sorts.ascending("asd", "qwe")))
);
}
}