一、前言
MongoDB是?个开源、?性能、?模式的?档型数据库,当初的设计就是?于简化开发 和?便扩展 ,是NoSQL数据库产品中的?种。是最像关系型数据库(MySQL)的?关系型数据库。
它?持的数据结构?常松散,是?种类似于 JSON 的 格式叫BSON ,所以它既可以存储?较复杂的数据类型,?相当的灵活。
二、集成实现
1.添加pom依赖
<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>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.配置 application.properties
## 端口号
server.port=8084
## 服务名称
spring.application.name=user-service
## 将服务注册到注册中心 eureka_service 的地址
eureka.client.service-url.defaultZone=http://localhost:8083/eureka/
## mongodb配置
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
#spring.data.mongodb.username=
#spring.data.mongodb.password=
spring.data.mongodb.database=db_test
# spring.data.mongodb.uri=mongodb://name:password@localhost:27017/test
3.创建实体类 User
package com.example.userservice.entity;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.util.Date;
@Data
@Document("User")
public class User{
@Id
private String id;
@Field("name")
private String name;
private String email;
private Integer age;
private Date createTime;
private Date updateTime;
}
4.编写UserController,实现 mongodb增删改查
4.1 新增(insert、insertAll)
新增(insert)
@Autowired
private MongoTemplate mongoTemplate;
@RequestMapping("/add")
public User addUser(@RequestBody User user){
user.setCreateTime(new Date());
return mongoTemplate.insert(user);
}
批量新增(insertAll)
@PostMapping("/batchInsert")
public Result batchInsert(@RequestBody List<User> userList){
mongoTemplate.insertAll(userList);
return Result.success();
}
4.2 删(remove)
删除(remove):根据实体类对象删除
@RequestMapping("/remove")
public Result remove(@RequestParam("id") String id){
User user = new User();
user.setId(id);
DeleteResult deleteResult =mongoTemplate.remove(user);
return Result.success(deleteResult.getDeletedCount());
}
删除(remove):根据条件(Query对象)删除---- 推荐使用这个
@RequestMapping("/removeByQuery")
public Result removeByQuery(@RequestParam("id") String id){
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
DeleteResult deleteResult =mongoTemplate.remove(query,User.class);
return Result.success(deleteResult.getDeletedCount());
}
4.3 改(updateFirst、updateMulti、upsert)
更新一条记录(updateFirst):更新匹配条件的第一条数据
@RequestMapping("/updateFirst")
public Result updateFirst(@RequestBody User user){
user.setUpdateTime(new Date());
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(user.getId()));
Update update = new Update();
update.set("name",user.getName());
update.set("age",user.getAge());
update.set("email",user.getEmail());
update.set("updateTime",new Date());
UpdateResult updateResult =mongoTemplate.updateFirst(query,update,User.class);
return Result.success(updateResult.getMatchedCount());
}
更新(updateMulti):更新匹配条件的全部数据
@RequestMapping("/updateMulti")
public Result updateMulti(@RequestBody User user){
user.setUpdateTime(new Date());
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(user.getId()));
Update update = new Update();
update.set("name",user.getName());
update.set("age",user.getAge());
update.set("email",user.getEmail());
UpdateResult updateResult =mongoTemplate.updateMulti(query,update,User.class);
return Result.success(updateResult.getMatchedCount());
}
更新(upsert)mongoTemplate.upsert(query,update,User.class):如果数据不存在就增加一条记录
@RequestMapping("/upsert")
public Result upsert(@RequestBody User user){
user.setUpdateTime(new Date());
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(user.getId()));
Update update = new Update();
update.set("name",user.getName());
update.set("age",user.getAge());
update.set("email",user.getEmail());
UpdateResult updateResult =mongoTemplate.upsert(query,update,User.class);
return Result.success(updateResult.getMatchedCount());
}
4.4 查(findAll、find、findOne)
查询全部 findAll
@RequestMapping("/all")
public Result getAll(){
List<User> list = mongoTemplate.findAll(User.class);
return Result.success(list);
}
条件查询 或(or)
@RequestMapping("/findQuery")
public Result findQuery(){
Criteria criteria1=new Criteria();
criteria1.and("id").is("001");
Criteria criteria2=new Criteria();
criteria2.and("name").is("张三");
Criteria criteria = new Criteria();
criteria.orOperator(criteria1,criteria2);
Query query = new Query();
query.addCriteria(criteria);
List<User> list = mongoTemplate.find(query,User.class);
return Result.success(list);
}
条件查询 且(and)
@RequestMapping("/findQueryAnd")
public Result findQueryAnd(){
Criteria criteria = new Criteria();
criteria.and("name").is("张三").and("age").gt(10);
Query query = new Query();
query.addCriteria(criteria);
List<User> list = mongoTemplate.find(query,User.class);
return Result.success(list);
}
条件查询 模糊查询(regex)
@RequestMapping("/findQueryRegex")
public Result findQueryRegex(){
Criteria criteria = new Criteria();
criteria.and("name").regex("^.*"+0+".*$");
Query query = new Query();
query.addCriteria(criteria);
List<User> list = mongoTemplate.find(query,User.class);
return Result.success(list);
}
条件查询 查总数(count)
@RequestMapping("/findQueryCount")
public Result findQueryCount(){
Criteria criteria = new Criteria();
criteria.and("name").regex("^.*"+0+".*$");
Query query = new Query();
query.addCriteria(criteria);
long count = mongoTemplate.count(query,User.class);
return Result.success(count);
}
条件查询 排序(sort)
@RequestMapping("/findQuerySort")
public Result findQuerySort(){
Criteria criteria = new Criteria();
criteria.and("age").gt(10);
Query query = new Query();
query.addCriteria(criteria);
Sort sort = Sort.by(Sort.Direction.DESC,"_id");
query.with(sort);
List<User> userList = mongoTemplate.find(query,User.class);
return Result.success(userList);
}
条件查询 分页
@RequestMapping("/page")
public Result list(String name,Integer offset,Integer limit){
Query query = new Query();
if(StringUtils.isNotBlank(name)){
query.addCriteria(Criteria.where("name").is(name));
}
Sort sort = Sort.by(Sort.Direction.DESC,"_id");
query.with(sort);
PageRequest page = PageRequest.of(offset-1,limit);
query.with(page);
List<User> userList = mongoTemplate.find(query,User.class);
return Result.success(userList);
}
聚合查询 Aggregation
@RequestMapping("/aggregation")
public Result aggregation(){
Criteria criteria = new Criteria();
criteria.and("age").gt(10);
Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
Aggregation.group("age").count().as("total"),
Aggregation.sort(Sort.Direction.DESC,"total"));
AggregationResults<UserVO> aggregationResults = mongoTemplate.aggregate(aggregation,"User", UserVO.class);
List<UserVO> userList = aggregationResults.getMappedResults();
return Result.success(userList);
}
查询单条记录
@RequestMapping("/findOne")
public Result findOne(){
Criteria criteria = new Criteria();
criteria.and("age").gt(16);
Query query = new Query();
query.addCriteria(criteria);
Sort sort = Sort.by(Sort.Direction.DESC,"_id");
query.with(sort);
User user = mongoTemplate.findOne(query,User.class);
return Result.success(user);
}
获取数据库中的所有文档集合
@RequestMapping("/findAllCollection")
public Result findAllCollection(){
Set<String> set = mongoTemplate.getCollectionNames();
return Result.success(set);
}
三、代码源码
可点击此处下载
|