关键词 :Aggregation.count()
protected Long getCountByTime(Long startTime, Long endTime) {
Criteria criteria = Criteria.where("uptime").gte(startTime).lte(endTime);
AggregationOptions.Builder builder = new AggregationOptions.Builder().allowDiskUse(true);
AggregationOptions aggregationOptions = builder.build();
TypedAggregation<Result> agg = Aggregation.newAggregation(Result.class,
Aggregation.match(criteria),
Aggregation.group("name"), // 按字段 name 进行分组查询
Aggregation.count().as("count"), // 将结果记录写到 count字段
Aggregation.project("count") // 结果只返回count
).withOptions(aggregationOptions);
AggregationResults<Result> aggregate = mongoTemplate.aggregate(agg, Record.class, Result.class);
List<ImsiRegionalStatic> mappedResults = aggregate.getMappedResults();
if (CollectionUtils.isNotEmpty(mappedResults)) {
return mappedResults.get(0).getCount();
}else {
return 0L;
}
}
多个Aggregation 是按先后顺序执行的,即后面一个在前面一个的基础上作筛选等操作
注意区分
Aggregation.group("deviceId").count() .as("count") 和 Aggregation.count().as("count")
前者得到的是 每个分组的记录数 ,也就是 相同 deviceId 的记录数
后者得到的是分组后的结果总记录数,即分组的数量