Spring MongoTemplate - 将聚合结果映射到集合(例如List和Map)
问题描述:
aggregate
方法MongoTemplate
返回AggregationResults<T>
,其中T
是对应于mongo集合的类。Spring MongoTemplate - 将聚合结果映射到集合(例如List和Map)
有时,我们只希望根据特定标准从该集合获取单个(说属性abc
)或几个属性(pqr
和xyz
)。在这些情况下,我们可以将整个集合检索到T
类或创建一个包含属性(abc
)或(pqr
,xyz
)的新类。
有没有办法将这些单个属性映射到List<String>
或两个属性作为HashMap<String, String>
中的键值对?
答
使用BasicDBObject
(支持LinkedHashMap
)/ Document
(来自2.0.0 spring mongo版本)以及java 8流方法将它们解析为集合类型。
单属性(abc
) - 列表类型
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());
多个属性(pqr, xyz
) - 地图型
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());
更新(从服务器读取)
单属性(abc
) - 列表类型
Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("abc").as("abc"));
List<String> singleResults = (List<String>) mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getUniqueMappedResult().get("abc");
多个属性(pqr
,xyz
) - 地图型
Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("pqr").as("pqr").push("xyz").as("xyz"));
Map multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getUniqueMappedResult();
什么你的建议是迭代汇集结果更风格的方式(让我知道,如果这种方式比使用传统的迭代更加高效for-each循环)。我一直在寻找一个解决方案,在MongoDB服务器中进行实际处理。 – Harish
好的,我根据你的评论更新了答案。请随时批评。 – Veeram