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

Har*_*ish 7 java spring spring-mvc mongodb mongotemplate

aggregateMongoTemplate返回的方法AggregationResults<T>,其中T是与mongo集合对应的类.

有时,我们只需要该集合中的单个(例如属性abc)或几个属性(pqrxyz),具体取决于特定条件.在这些情况下,我们可以将整个集合检索到T类中,也可以创建一个包含properties(abc)或(pqr,xyz)的新类.

有没有办法将这些单个属性映射到List<String>两个属性作为键值对HashMap<String, String>

use*_*814 7

使用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());
Run Code Online (Sandbox Code Playgroud)

多个属性(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());
Run Code Online (Sandbox Code Playgroud)

更新(从服务器读取)

单个属性(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");
Run Code Online (Sandbox Code Playgroud)

多个属性(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();
Run Code Online (Sandbox Code Playgroud)