MongoDB日常操作
最近项目中使用MongoDB进行存入统计相关的数据,便于查寻且提高效率。
首先在项目中引入MongoDB:
1.加入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
2.配置application.yml
spring: data: mongodb: host: ${MONGO_HOST:localhost} port: 27017 database: student_statistics # username: # password:
操作MongoDB
1.注入 MongoTemplate 类直接对MongoDB进行操作
@Autowired private MongoTemplate mongoTemplate;
2.1聚合查寻
//封装查询条件 List<AggregationOperation> operations = new ArrayList<>(); if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) { operations.add(Aggregation.match(Criteria.where("createTime").in(timeList))); } if (CollectionUtils.isNotEmpty(schoolIds)) { operations.add(Aggregation.match(Criteria.where("schoolId").in(schoolIds))); } // 聚合分组 operations.add(Aggregation.group("createTime") .count().as("totalNum") .sum("signNum").as("totalSignNum") ); // 列举要查寻的数据,并对聚合字段做别名(project后面的参数即为要查寻和显示的字段),否则聚合字段恒为_id operations.add(Aggregation.project("createTime","maybeContinueNum","alreadyContinueNum").and("createTime").previousOperation()); Aggregation aggregation = Aggregation.newAggregation(operations); AggregationResults<GeekDataContinueRateRangeOut> results = mongoTemplate.aggregate(aggregation, collection, Out.class);
List<GeekDataContinueRateRangeOut> queryResultList = results.getMappedResults();
2.2 普通查询并排序
//封装查询条件 Query query = new Query(); if (CollectionUtils.isNotEmpty(schoolIds)) { query.addCriteria(Criteria.where(StatisticsConst.QUERY_CONDITION_SCHOOLAREAID).in(schoolIds)); } if (StringUtils.isNotBlank(createTime)) { query.addCriteria(Criteria.where(StatisticsConst.QUERY_CONDITION_CREATETIME).is(createTime)); } long count = mongoTemplate.count(query, collectionName); Criteria criteria = new Criteria(); criteria.orOperator(Criteria.where(StatisticsConst.QUERY_CONDITION_REFUND_NUM).is(1), Criteria.where(StatisticsConst.QUERY_CONDITION_PRE_REFUND_NUM).is(1), Criteria.where(StatisticsConst.QUERY_CONDITION_CARRYOVER_REFUND_NUM).is(1)); query.addCriteria(criteria); query.with(Sort.by(Sort.Direction.DESC,StatisticsConst.QUERY_CONDITION_OUT_CLASS_DATE)); // 查寻 List<RefundOut> refundOuts = mongoTemplate.find(query, RefundOut.class, collectionName);
3.打印sql,在application.yml中配置log级别,即可在控制台打印执行的sql,但不能直接在Navicat执行,需要简单处理下格式。
logging:
level:
org.springframework.data.mongodb.core.MongoTemplate: DEBUG