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) – 地图类型
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();