实用 MongoTemplate 可实现简单的CRUD。
目前简单介绍下新增和分页查询
实用springboot2.x
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、写上配置文件
首先需要在MongoDB中新建一个数据库,使用use datadb;就可以
spring:
data:
mongodb:
uri: mongodb://192.168.108.129:27017,192.168.108.129:27018/datadb?slaveOk=true&replicaSet=testdb&write=1&readPreference=secondaryPreferred&connectTimeoutMS=300000
server:
port: 8081
3、在controller中注入
@Autowired
private MongoTemplate mongoTemplate;
4、使用
//批量新增数据,指定文档名
@RequestMapping(value = "add")
public void add(){
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Map<String, Object> map = new HashMap<>();
for (int j = 0; j < 20; j++) {
map.put("key"+i +"_" + j, i*j);
}
list.add(map);
}
mongoTemplate.insert(list, "add_demo1");
}
@RequestMapping(value = "/query")
public List<Map> query(@RequestParam(value = "page") Integer currentPage,
@RequestParam("size") Integer pageSize,
@RequestParam("one") Boolean flag){
Query query = new Query();
if(flag){
query.addCriteria(Criteria.where("key1_1").is(1));
}
long count = mongoTemplate.count(query, Map.class, "add_demo1");
// 需要注意,需要放在count后面。这儿还可以传入排序Sort
Pageable pageable = PageRequest.of(currentPage, pageSize);
query.with(pageable);
List<Map> mapList = mongoTemplate.find(query, Map.class, "add_demo1");
//TODO 组装分页返回对象
System.out.println(count);
return mapList;
}