我想使用 mongotemplate 获取聚合的结果总数。
为了澄清 - 对于查询,我们可以使用:mongoTemplate.count(query, collectionName)
,它获取结果数量而不考虑限制/跳过。
但是,我找不到 mongotemplate 聚合的类似内容... 需要总结果是因为我们使用分页,并且需要知道没有限制/跳过的总数。
编辑:例如,如果我有以下包含 10 个文档的集合 A:
{ 字段1:..., 字段2:..., },...
我可以创建一个查询来使用 mongotemplate 获取文档:
Query query = new Query();
query.limit(5);
List<?> queryResults = this.mongoTemplate.find(query, A.class , "A") // will return only 5 results
long count = this.mongoTemplate.count(query, collectionName); // will return 10, because that's the total number result
现在,如果我有一个聚合而不是查询:
List<AggregationOperation> aggregationOperations = new ArrayList<AggregationOperation>();
aggregationOperations.add(Aggregation.match(...));
aggregationOperations.add(Aggregation.group(...));
aggregationOperations.add(Aggregation.limit(someLimit));
AggregationResults<?> aggregationResults =
this.mongoTemplate.aggregate(
Aggregation.newAggregation(aggregationOperations), "A",
AggregationResults.class);
我想要某种方法来获取聚合中的结果总数 - 类似于查询的“计数”。
最佳答案
你可以这样做
operations.add(Aggregation.group().count().as("count"));
Document rawResults = getMongoTemplate().aggregate(
Aggregation.newAggregation(operations),
collectionName,
entityClass)
.getRawResults();
List<Map<String, Object>> results = (List<Map<String, Object>>) rawResults.get("results");
if (CollectionUtils.isNotEmpty(results)
&& results.get(0) != null
&& results.get(0).containsKey("count")) {
Integer count = (Integer) results.get(0).get("count");
return count.longValue();
}
return 0;
}
关于java - Mongotemplate聚合-获取结果数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34590077/