Spring MongoTemplate - Mapping aggregation result to collections (e.g. List and Map)
Use BasicDBObject
(backed by LinkedHashMap
) / Document
(from 2.0.0 spring mongo version) along with java 8 stream methods to parse them into collection types.
Single Property (abc
) - List type
Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("abc"));List<String> singleResults = mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getMappedResults().stream().map(item -> item.getString("abc")).collect(Collectors.toList());
Multiple properties (pqr, xyz
) - Map type
Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("pqr, xyz"));List<Map> multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getMappedResults().stream().map (item -> (LinkedHashMap) item).collect(Collectors.toList());
Update ( Reading from server )
Single Property (abc
) - List type
Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("abc").as("abc"));List<String> singleResults = (List<String>) mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getUniqueMappedResult().get("abc");
Multiple properties (pqr
, xyz
) - Map type
Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("pqr").as("pqr").push("xyz").as("xyz"));Map multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getUniqueMappedResult();
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());