MongoTemplate 聚合查询

一、概述

1. 聚合的表达式

MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似sql语句中的 count(*)。

下表展示了一些聚合的表达式:

表达式 描述 实例
$sum 计算总和。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avg 计算平均值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$min 获取集合中所有文档对应值得最小值。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$max 获取集合中所有文档对应值得最大值。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
$push 在结果文档中插入值到一个数组中。 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
$addToSet 在结果文档中插入值到一个数组中,但不创建副本。 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
$first 根据资源文档的排序获取第一个文档数据。 db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])
$last 根据资源文档的排序获取最后一个文档数据 db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

2. 管道的概念

管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。

MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。

表达式:处理输入文档并输出。表达式是无状态的,只能用于计算当前聚合管道的文档,不能处理其它的文档。

这里我们介绍一下聚合框架中常用的几个操作:

  • $project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。
  • $match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
  • $limit:用来限制MongoDB聚合管道返回的文档数。
  • $skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。
  • $unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
  • $group:将集合中的文档分组,可用于统计结果。
  • $sort:将输入文档排序后输出。
  • $geoNear:输出接近某一地理位置的有序文档。

3. 聚合查询示例:

1

2

3

4

db.articles.aggregate( [

                        { $match : { score : { $gt : 70, $lte : 90 } } },

                        { $group: { _id: null, count: { $sum: 1 } } }

                       ] );

但是在代码中要如何实现类似以上功能呢?

二、代码实现(sum求和)

功能描述:

  1. 当name和course同时传参时,按id分组,统计总分数
  2. 按name分组,统计相同name的总分数
  3. 按course分组,统计总分数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

public double getTotleScoreWithMongoTemplate(StudentScore studentScore) {

  //封装查询条件

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

  if (StringUtils.isEmpty(studentScore.getName()) && StringUtils.isEmpty(studentScore.getCourse())){

    //totleScore为StudentScore类中新建的属性,用于接收统计后的总分数;当然也可以使用score(或其他属性)接收

    operations.add(Aggregation.group("id").sum("score").as("totleScore"));

  }

  if (!StringUtils.isEmpty(studentScore.getName())) {

    operations.add(Aggregation.match(Criteria.where("name").is(studentScore.getName())));

    operations.add(Aggregation.group("name").sum("score").as("totleScore"));

  }

  if (!StringUtils.isEmpty(studentScore.getCourse())) {

    operations.add(Aggregation.match(Criteria.where("course").is(studentScore.getCourse())));

    operations.add(Aggregation.group("course").sum("score").as("totleScore"));

  }

  Aggregation aggregation = Aggregation.newAggregation(operations);

  //查询、并获取结果

  AggregationResults<StudentScore> results = mongoTemplate.aggregate(aggregation, "studentScore", StudentScore.class);

  double totleScore = results.getUniqueMappedResult().getTotleScore();

  return totleScore;

}

猜你喜欢

转载自blog.csdn.net/wmq880204/article/details/114294947
今日推荐