Bootstrap

Mongo 常用需求整理

1. mongo 按照时间区间 + 年-月分组统计

		Date begin = DateUtil.parse(String.valueOf(year) + DAY_OF_MONTH);
        Date end = DateUtil.parse(String.valueOf(year + 1) + DAY_OF_MONTH);
        // 初始化当年 12月
        List<String> timeList = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            DateTime dateTime = DateUtil.offsetMonth(begin, i);
            timeList.add(DateUtil.format(dateTime, YEAR_MONTH));
        }
        Criteria criteria = new Criteria();
        criteria.and(MongoFieldsConstants.COLLECT_MONTH).in(timeList);
        List<AggregationOperation> operations = new ArrayList<>();
        //查询条件,字段在我指定的日期中
      operations.add(Aggregation.project("catalog_id","status","_id","origin_department","theme_id","create_time")
                .andExpression("{$dateToString:{ format:'%Y-%m',date: '$create_time', timezone: 'Asia/Shanghai'}}").as("$collectMonth")
                .andExpression("{$dateToString:{ format:'%Y',date: '$create_time', timezone: 'Asia/Shanghai'}}").as("$year")
                .andExpression("{$dateToString:{ format:'%m',date: '$create_time', timezone: 'Asia/Shanghai'}}").as("$month"));
        operations.add(Aggregation.match(criteria));
        //按月分组统计;group分组,会将分组字段放入_id中,如果需要显示该字段,可以用聚合函数中的其中一个标记一下
                 operations.add(Aggregation.group(MongoFieldsConstants.THEME_ID,MongoFieldsConstants.ORIGIN_DEPARTMENT,MongoFieldsConstants.COLLECT_MONTH)
                    .count().as(MongoFieldsConstants.ROWS)
                    .first("year").as("year")
                    .first("month").as("month"));
        
        Aggregation aggregation = Aggregation.newAggregation(operations);
        return mongoTemplate.aggregate(aggregation, Constants.DMS_COLLECTION_NAME_DATA_RESOURCE, DataResVisualDTO.class).getMappedResults();

2. mongo 分页统计

  • find
        //创建排序模板Sort
        Sort sort = new Sort(Sort.Direction.DESC, "creationDate");//创建分页模板Pageable 
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("create_time")));
        Query query = new Query().with(pageable);

  • Aggregation
		// 排序规则
		Sort sort = Sort.by(Sort.Direction.ASC, "_id");
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.group("source_type").count().as("amount"),
                Aggregation.sort(sort)
        );

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;