2. mongodb Aggregation 语法
1. 分组统计
Criteria criteria = Criteria.where("userId").is(userId) .and("stage").is(stage) .and("ifFreeGoods").is(true) .and("createTime").gte(time); Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria), Aggregation.group("lessonId").sum("playCount").as("playCount"), Aggregation.project() .and("_id").as("lessonId") .and("playCount").as("playCount") ); AggregationResults<BasicDBObject> aggregationResults = mongoTemplate.aggregate( aggregation, CoursePlayStatisticsEntity.class, BasicDBObject.class ); if (Objects.isNull(aggregationResults) || CollectionUtils.isEmpty(aggregationResults.getMappedResults())) { return 0L; } List<BasicDBObject> results = aggregationResults.getMappedResults(); return results.stream().mapToLong(e -> { return e.getLong("playCount"); }).sum();
2. 不分组统计
如果不分组获取统计值,那么只是需要将 group 分组传 空
Criteria criteria = Criteria.where("userId").is(userId) .and("stage").is(stage) .and("ifFreeGoods").is(true) .and("createTime").gte(time); Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria), Aggregation.group().sum("playCount").as("playCount"), Aggregation.project() .and("playCount").as("playCount") ); AggregationResults<BasicDBObject> aggregationResults = mongoTemplate.aggregate( aggregation, CoursePlayStatisticsEntity.class, BasicDBObject.class ); if (Objects.isNull(aggregationResults) || CollectionUtils.isEmpty(aggregationResults.getMappedResults())) { return 0L; } List<BasicDBObject> results = aggregationResults.getMappedResults(); return results.stream().mapToLong(e -> { return e.getLong("playCount"); }).sum();
3. 条件查询,结果处理
db.ussi.aggregate( [ { $match: { tsct: { $gte: 1514736000000 }, wcts: { $gt: 0 } } }, { $project: { butp: 1, uid: 1, tsct: 1, wcts2S: { "$ifNull": ["$wcts", 0] }, "divide": { "$divide": [{ "$ifNull": ["$wcts", 0] }, 60] }, date2Str: { $dateToString: { format: "%Y-%m-%d %H:%M:%S", date: { "$add": [new Date(0), "$tsct", 28800000] } } } } }, { $sort: { wcts2S: - 1 } } ] )
包含:
1. tsct 日期格式化
2. wcts 非空判断,除 60 处理
3. sort 排序
参考资料,管道聚合计算:https://www.bbsmax.com/A/E35pL2e85v/