【问题标题】:Spring MongoTemplate - Mapping aggregation result to collections (e.g. List and Map)Spring MongoTemplate - 将聚合结果映射到集合(例如 List 和 Map)
【发布时间】:2017-12-10 12:13:00
【问题描述】:

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

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

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

【问题讨论】:

标签: java spring mongodb spring-mvc mongotemplate


【解决方案1】:

使用 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");

多个属性(pqrxyz) - 地图类型

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 服务器中进行实际处理的解决方案。
  • 好的,我已经根据您的评论更新了答案。请随时批评。
【解决方案2】:

使用 Spring-data-mongodb 2.0.10mongo-java-driver 3.6.4 我将上面的答案更改为使用 Document而不是 BasicDBObject 到适合我的版本:

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());

【讨论】:

    猜你喜欢
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2020-09-28
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多