我有一个聚合:
AggregationResults<Integer> result = mongoTemplate.aggregate(
Aggregation.newAggregation(
Aggregation.group().count().as("value"),
Aggregation.project("value").andExclude("_id"),
MyData.class, Integer.class);
在 mongo shell 中,当我不必映射对象时,我得到: { "value": 2 }
但是,在尝试映射此单独值时出现以下错误:org.springframework.data.mapping.model.MappingException:找不到 java.lang.Integer 的映射元数据
当我只想获取单个 java 原语时,我可以不必创建新的输出类型类吗?
注意:我将采用这种方法而不是 db.collection.count() 来解决此处所述的分片不准确问题 - https://docs.mongodb.com/manual/reference/method/db.collection.count/#sharded-clusters
最佳答案
AggregationResults<DBObject> result = mongoTemplate.aggregate(
Aggregation.newAggregation(
Aggregation.group().count().as("value"),
Aggregation.project("value").andExclude("_id"),
MyData.class, DBObject.class);
int count = (Integer) result.getUniqueMappedResult().get("value");
所以,这并不完全是我想要的,因为我仍然需要遍历一个对象,但它并不比以前有更多的代码,而且我不需要创建另一个类作为outputType。
关于java - 从 mongo 聚合获取 java 原语,无需新的输出类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43687074/