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;

}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菠萝-琪琪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值