1.maven的pom.xml中引入jar包:
org.springframework.boot
spring-boot-starter-data-mongodb
2.application.properties中配置mongodb地址:
## mongodb ##
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/test
若连接需要账号验证,改为:
spring.data.mongodb.uri=mongodb://root:[email protected]:27017/test
3.使用
3.1在使用类中直接注入
@Autowired
MongoTemplate mongoTemplate;
Query query = new Query(Criteria.where("type").is(type).and("name").is(name));
List reportRealtimeModel = mongoTemplate.find(query, ReportRealtime.class, "reportRealtimeModel");
String alias = "nowNum";
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("name").is(name)),
Aggregation.group("age").count().as(alias)
);
AggregationResults
3.3多条件聚合查询
String alias = "nowNum";
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("name").is(name).and("size").is(size)),
//Aggregation.match(Criteria.where("size").is(size)),
Aggregation.group("age").count().as(alias)
);
AggregationResults results= mongoTemplate.aggregate(aggregation, "testCollection", Map.class);
List mappedResults = results.getMappedResults();
if (mappedResults != null && mappedResults.size() > 0) {
Integer num = (Integer) mappedResults.get(0).get(alias);
return num;
}
Query query = new Query(Criteria.where("name").is(name).and("size").is(size).and("age").is(age))
.skip((page.getPageNum()-1)*page.getPageSize())
.limit(page.getPageSize());
List list= mongoTemplate.find(query, JavaEntity.class, "testCollection");
long totalSize = mongoTemplate.count(query, JavaEntity.class, "testCollection");
page.setTotalSize((int) totalSize);
注意:分页查询是最基本的查询,看网上说法,这种查询会导致mongodb的全表查询,即整个collection的查询,所以collection的数据量大的时候不建议使用这种方式,具体可百度mongodb的分页优化,暂时自己没有亲测。
Criteria criteria = new Criteria();
if (groupIdList != null && groupIdList.size() > 0) {
criteria = criteria.and("groupId").in(groupIdList);
}
if (terminalType != null) {
criteria = criteria.and("terminalType").is(terminalType);
}
if (StringUtils.isNotBlank(state)) {
criteria = criteria.and("state").is(state);
}
if (StringUtils.isNotBlank(terminalId)) {
//多字段模糊匹配
Pattern pattern = Pattern.compile("^.*" + terminalId + ".*$", Pattern.CASE_INSENSITIVE);
criteria = criteria.orOperator(Criteria.where("terminalId").regex(pattern), Criteria.where("terminalName").regex(pattern));
}
Query query = new Query(criteria).skip((pageNum - 1) * pageSize).limit(pageSize);