1. 配置
1.1 依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
1.2 配置文件
spring:
data:
mongodb:
# uri: mongodb://127.0.0.1:27017/concrete # 未开启安全协议时无需密码
uri: mongodb://Tinyspot:123456@127.0.0.1:27017/concrete
2. 实战
2.1 查询
@RestController
@RequestMapping("/mongo")
public class MongoController {
@Resource
private MongoTemplate mongoTemplate;
@GetMapping("/findAll")
public String findAll() {
List<UserVO> all = mongoTemplate.findAll(UserVO.class);
return JSON.toJSONString(all);
}
@GetMapping("/findUser")
public String findUser(String name) {
Query query = new Query(Criteria.where("name").is(name));
UserVO user = mongoTemplate.findOne(query , UserVO.class);
return user.toString();
}
}
2.2 相关注解
@Data
@Document(collection = "user")
public class UserVO implements Serializable {
private static final long serialVersionUID = 5274857955858412692L;
private String id;
private String name;
private Integer age;
}
@Document
作⽤在类上,指定集合名称
@Id
作⽤在成员变量、⽅法上,映射为⽂档 _id
@Field
作⽤在成员变量、⽅法上,指定在⽂档中 key 的名称,默认为成员变量名
2.3 操作
@PostMapping("/insert")
public String insert(UserVO userVO) {
UserVO insert = mongoTemplate.insert(userVO);
return JSON.toJSONString(insert);
}
/**
* 报错一:java.lang.IllegalStateException: No primary or single unique constructor found for interface java.util.List
* 接收参数加上:@RequestBody
*/
@PostMapping("/insertBatch")
public String insertBatch(@RequestBody List<UserVO> users) {
Collection<UserVO> insert = mongoTemplate.insert(users, UserVO.class);
return JSON.toJSONString(insert);
}
@PostMapping("/updateFirst")
public Long updateFirst(UserVO userVO) {
// 更新条件
Query query = new Query(Criteria.where("id").is(userVO.getId()));
// 更新值
Update update = new Update()
.set("name", userVO.getName())
.set("age", userVO.getAge());
// 更新查询满足条件的文档数据(第一条)
UpdateResult result = mongoTemplate.updateFirst(query, update, UserVO.class);
return result.getMatchedCount();
}
@GetMapping("/deleteById")
public Long deleteUserById(String id) {
Query query = new Query(Criteria.where("_id").is(id));
DeleteResult result = mongoTemplate.remove(query, UserVO.class);
return result.getDeletedCount();
}
@GetMapping("/deleteByName")
public Long deleteByName(String name) {
Query query = new Query(Criteria.where("name").is(name));
DeleteResult result = mongoTemplate.remove(query, UserVO.class);
return result.getDeletedCount();
}
网友评论