java mango_java 操作mango 实现增删改查

1.pom.xml

org.springframework.boot

spring-boot-starter-data-mongodb

2.0.0.RELEASE

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 findListMongo(){

Pattern pattern = Pattern.compile("^1.*$",Pattern.CASE_INSENSITIVE);

Query query = new Query(Criteria.where("phone").regex(pattern));

List 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 pageCollects = mongoTemplate.find(query, PageCollect.class);

// 按照年龄顺序

query.with(Sort.by(new Sort.Order(Sort.Direction.ASC, "age"))

List 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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值