最近在将之前python+mongodb的项目用java重构,所以不可避免的涉及到java操作mongodb,这里采用的数据库框架是spring-data-mongodb,至于为什么采用这个框架,可能类似于JPA的形式直接打动了我。在实际的使用中,确实没有python方便,其中遇到了一些问题,这里记下来,以便自己回忆,也希望能帮助大家。
数据格式:
单层操作 :修改值1,order_name
Query query=new Query(Criteria.where("_id").is("ObjectId("5cda615557f78256fa4c6741")").and("answers.order_number").is(1));
Update update=new Update();
update.set("answers.$.order_name","修改的值1!!!");
//个人理解:$相当于占位符,可以在查询更新时,及时的传值
mongoTemplate.updateFirst(query,update,"answer:表名");
双层操作:修改值2,hit_keywords
Query query=new Query(Criteria.where("_id").is("5cda615557f78256fa4c6741"));
Update update=new Update();
update.set("answers.$[first].answer_list.$[second].hit_keywords","修改的值2!!!");
// 个人理解:$[]可以用来指定位置,并通过 filterArray过滤器进行过滤
update.filterArray("first.order_number",1);
update.filterArray("second.q_number",2);
mongoTemplate.updateFirst(query,update,"answer:表名");
多层指令:可以通过$[]设置多个占位符修改
注意:$[]只在mongodb3.6版本及以上才能使用,否则会报错filterArray指令不存在;
网友评论