java中使用mongoTemplate进行group分组统计的问题

今天练习在java中使用mongodb,进行分组,刚开始没有思路,后来通过查资料,大概写了一个demo,以下是分组在java中用到的group分组代码:

这是mongodb中的数据:
mongodb数据库中的数据
这是java中的代码:

String[] field = {"teacher_name","teacher_synopsis"}; 		//分组的依据,根据那些参数进行分组
Aggregation aggregation1 = Aggregation.newAggregation(
				Aggregation.match(Criteria.where("collect_data").is(month)),	//条件筛选    可以跟好几个条件
			    Aggregation.group(field).count().as("sum"),		//分组统计收藏量    ,as 起别名
			    Aggregation.sort(new Sort(Sort.Direction.DESC, "sum")),	//按照收藏量倒叙排序
			    Aggregation.skip(0),	//跳过前0条		skip 和  limit  是分页用到的
			    Aggregation.limit(2)	//往后查2条
		);
		//构建查询条件		//这是我自己需要拿出来的数据,放到集合中
		ArrayList<String> params = new ArrayList<>();
		//执行
		AggregationResults<BasicDBObject> outputTypeCount1 = mongoTemplate.aggregate(aggregation1, "collect", BasicDBObject.class);
		//迭代器进行迭代
		for (Iterator<BasicDBObject> iterator = outputTypeCount1.iterator(); iterator.hasNext(); ) {
			 DBObject obj = iterator.next();
			 //拿出老师的名字
			 String string = obj.get("teacher_name").toString();
			 params.add(string);
		}

因为是第一次遇到这种问题,所以记录下来。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值