java - Spring MongoTemplate - 将聚合结果映射到集合(例如 List 和

aggregate MongoTemplate的方法|返回 AggregationResults<T> , 其中 T是对应mongo集合的类。

有时,根据特定标准,我们只需要该集合中的单个(例如属性 abc )或几个属性( pqrxyz )。在这些情况下,我们可以将整个集合检索到 T类或创建一个包含属性(abc)或(pqrxyz)的新类。

有没有办法将这些单一属性映射到 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");

多个属性(pqrxyz) - 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/

相关文章:

javascript - 为已登录的用户手动创建 Passport session

node.js - 我应该使用什么数据类型来使用 MongoDB 存储图像?

c# - ReadBsonType 只能在 State 为 Type 时调用,不能在 State 为

mongodb - Meteor 1.4.1.1 上副本集的正确 MONGO_URL 设置是什么

node.js - Mongoose 类型错误 : User is not a constructo

node.js - 查找未邀请任何用户的用户

mongodb - 使用键值对将 mongo 数组转换为对象

java - 如何防止连接池在 mongodb 上使用 java 驱动程序关闭?

json - 使用 Python 从 MongoDB 文档创建 JSON 文件

node.js - Node/Express - 保护客户端/服务器之间通信的好方法