aggregate
MongoTemplate
的方法|返回 AggregationResults<T>
, 其中 T
是对应mongo集合的类。
有时,根据特定标准,我们只需要该集合中的单个(例如属性 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
) - map 类型
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
) - map 类型
Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("pqr").as("pqr").push("xyz").as("xyz"));
Map multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getUniqueMappedResult();
关于java - Spring MongoTemplate - 将聚合结果映射到集合(例如 List 和 Map),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44949720/