java mongodb Aggregation的一些常用方法

在开发中,我们会遇到查询mongodb中的数据,但是限定条件比较多,
那如何解决呢?笔者整理了一些常用的限定条件,废话少说,上代码:

 Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("requestTime").gte(start).lte(new Date())),
                Aggregation.match(Criteria.where("userNo").is(userNo)),
                Aggregation.match(Criteria.where("userNo").is(userNo)),
                Aggregation.group("layerguid").count().as("sum")
                        .first("layerguid").as("layerguid")
                        .first("status").as("status")
                        .first("requestTime").as("requestTime"),
                 Aggregation.sort(Sort.by("sum").descending()),
                 Aggregation.skip(page>1?(page-1)*size:0),
                 Aggregation.limit(size)
        );

        List<Map> results = mongoTemplate.aggregate(aggregation, "mongodb表名", Map.class).getMappedResults();
match:代表的是where条件,
gte:>
lte:<
is:==
group:分组
count:数量
first:过滤显示的属性
sort:排序
skip和limit:组合使用为分页
page:当前页
size:每页中显示的条数

这几个属性的顺序不要打乱,打乱会报错的。
想要查询一段时间内的数据,便可以使用.gte(start).lte(new Date())
start的是开始时间,获得方式如下:

 		String  startTime = null;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();

        if(type.equals("1")){
            //过去七天
            c.setTime(new Date());
            c.add(Calendar.DATE, - 7);
            Date m = c.getTime();
            startTime= format.format(m);
        }

        if(type.equals("2")){
            //过去一月
            c.setTime(new Date());
            c.add(Calendar.MONTH, -1);
            Date m = c.getTime();
            startTime= format.format(m);
        }

        if(type.equals("3")){
            //过去三个月
            c.setTime(new Date());
            c.add(Calendar.MONTH, -3);
            Date m3 = c.getTime();
            startTime = format.format(m3);
        }

        if(type.equals("4")){
            //过去一年
            c.setTime(new Date());
            c.add(Calendar.YEAR, -1);
            Date y = c.getTime();
            startTime = format.format(y);
        }


        Date start = null;

        try {
            start = format.parse(startTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

根据实际需求得时间段即可。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐