2

我想使用 mongotemplate 获取聚合的结果总数。

澄清一下 - 对于查询,我们可以使用: mongoTemplate.count(query, collectionName),它在不考虑限制/跳过的情况下获取结果数量。

但是,对于 mongotemplate 聚合,我找不到类似的东西......因为我们使用分页,所以需要总结果,并且需要知道没有限制/跳过的总数。

编辑:例如,如果我有以下包含 10 个文档的集合 A:

{ field1 : ... , field2 : ... , }, ...

我可以创建一个查询来使用 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);

我想要某种方法来获取聚合中的结果总数 - 类似于查询的“计数”。

4

1 回答 1

2

你可以这样做

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;

}
于 2020-01-13T18:33:03.520 回答