Spring MongoTemplate - Mapping aggregation result to collections (e.g. List and Map)

Viewed 9878

aggregate method of MongoTemplate returns AggregationResults<T>, where T being the class that corresponds to mongo collection.

Sometimes, we only want the single (say property abc) or a couple of properties (pqr and xyz) from that collection depending on particular criteria. In these cases, we can either retrieve the whole collection into T class or create a new class that contains properties (abc) or (pqr, xyz).

Is there a way to map these single property to List<String> or two properties as a key-value pair in HashMap<String, String>?

2 Answers

Using Spring-data-mongodb 2.0.10 and mongo-java-driver 3.6.4 I changed the answer above to use Document instead of BasicDBObject onto a version that worked for me :

Aggregation aggregation = newAggregation(
                         //some aggregation code
                         );


    List<Document> result = mongoTemplate.aggregate(aggregation, "my_collection", Document.class).getMappedResults();
    List<String> resultList= result.stream().map(item -> item.get("_id").toString()).collect(Collectors.toList());
Related