java 操作mango 实现增删改查

1.pom.xml

<!-- springboot 整合 mongodb   -->
   <dependency> 
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-data-mongodb</artifactId>
	    <version>2.0.0.RELEASE</version>
   </dependency>

2.导入对象

@Autowired
private MongoTemplate mongoTemplate;

3.CRUD

插入数据

User ser = new SysUser("1","李白",18,"1811111111");
mongoTemplate.insert(sysUser, "userList");

查询数据

//查询一条
    public User findMongo(){
        Pattern pattern = Pattern.compile("^.*8$",Pattern.CASE_INSENSITIVE);
		Query query = new Query(Criteria.where("phone").regex(pattern));
		User findOne = mongoTemplate.findOne(query,User.class,"userList");
		return findOne;
}

//查多条
    public List<User> findListMongo(){
        Pattern pattern = Pattern.compile("^1.*$",Pattern.CASE_INSENSITIVE);
		Query query = new Query(Criteria.where("phone").regex(pattern));
		 List<User> findList = mongoTemplate.fin(query,User.class,"userList");
		return findList;
}
// 多个查询条件
     Query query = new Query(
                Criteria.andOperator(
                                Criteria.where("age").gte(15),
                                Criteria.where("age").lte(25)
                        ));
        query.with(Sort.by(new Sort.Order(Sort.Direction.ASC, COUNT_TIME)));
        List<User> pageCollects = mongoTemplate.find(query, PageCollect.class);
        // 按照年龄顺序
        query.with(Sort.by(new Sort.Order(Sort.Direction.ASC, "age"))
        List<User> pageCollects = mongoTemplate.find(query, User.class);

修改数据

//更新
public int update() {
	Query query = new Query(); 
	query.addCriteria(Criteria.where("_id").is(1));  //_id区分引号 "1"和1
	Update update = Update.update("name", "zzzzz");
//	WriteResult upsert = mongoTemplate.updateMulti(query, update, "userList"); //查询到的全部更新
//	WriteResult upsert = mongoTemplate.updateFirst(query, update, "userList"); //查询更新第一条
	WriteResult upsert = mongoTemplate.upsert(query, update, "userList");      //有则更新,没有则新增
	return upsert.getN();       //返回执行的条数
	}


//添加内嵌文档数据(有则直接加入,没有则进行新增)
	public int update1() {
		Query query = Query.query(Criteria.where("_id").is("11"));
		SysUser user = new SysUser(1,"1","lisi","19999998745");
		Update update = new Update();
		update.addToSet("users", user);
		WriteResult upsert = mongoTemplate.upsert(query, update, "userList");
		return upsert.getN();
	}

删除数据

        public void delete(){
            Query query = Query.query(Criteria.where("name").is("李白"));
	    mongoTemplate.remove(query, User.class);    
        }

posted @ 2019-12-25 16:14  Milford  阅读(550)  评论(0编辑  收藏  举报