mongodb某个字段distinct计数问题

发布时间 2023-03-23 18:04:01作者: 沙漠皇帝

方式1

List<AggregationOperation> operations = new ArrayList<>();

operations.add(Aggregation.match(Criteria.where("created_at").gte(begin).lte(end)));
operations.add(Aggregation.match(Criteria.where("deleted_at").isNull()));

operations.add(Aggregation.group("user_id").count().as("total"));
Aggregation agg = Aggregation.newAggregation(operations);
AggregationResults<TotalDto> result = mongoTemplate.aggregate(agg, "cycling", TotalDto.class);
var count = result.getMappedResults().size();
return (long) count;

方式2

List<AggregationOperation> operations = new ArrayList<>();

operations.add(Aggregation.match(Criteria.where("created_at").gte(begin).lte(end)));
operations.add(Aggregation.match(Criteria.where("deleted_at").isNull()));

operations.add(Aggregation.group("user_id"));
operations.add(Aggregation.count().as("total"));
Aggregation agg = Aggregation.newAggregation(operations);
TotalDto dto = mongoTemplate.aggregate(agg, "cycling", TotalDto.class).getUniqueMappedResult();
if (Objects.nonNull(dto)) {
	return dto.getTotal();
}
return 0L;