一、java操作mongoDB数据库
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
@Autowired
private MongoTemplate mongoTemplate;
//获取一条数据
String id="id";
//query 查询条件
Query query = new Query(Criteria.where("_id").is(id));
//Document集合名字
Map test = mongoTemplate.findOne(query, Map.class, "Document");
//添加数据
String id="id";
map.put("_id",id);
//Map中添加_id作为id Document集合名字
mongoTemplate.save(map,"Document");
//修改数据
String id="id";
//query作为修改条件
Query query = new Query(Criteria.where("_id").is(id));
Update update = new Update();
//attrMap接收到Map
attrMap.forEach((key,value)->update.set(String.valueOf(key),value));
//Document集合名字
mongoTemplate.updateFirst(query, update,Map.class,"Document");
二、mongoTemplate多条件分页查询
Query query = new Query();
//分页
Pageable pageable = PageRequest.of(pageIndex, pageSize);
query.with(pageable);
//判断传入的值是否为null或空,不为就添加条件
if(deviceId != null && deviceId != ""){
query.addCriteria(Criteria.where("deviceId").is(deviceId)); }
if(homeId != null && homeId != ""){
query.addCriteria(Criteria.where("homeId").is(homeId)); }
//多条件查询
List<Map> deviceLogList = mongoTemplate.find(query, Map.class, "DeviceLog");