本文是使用JAVA程序操作MongoDB数据库。里面提供了各种更新数据的方法,查询的各种方法会在后面进行更新。
本文只是提供了数据库更新操作的一些方法。
数据库数据和字段如下:
对于更新数据,我将更新数据的方法抽象出来成为单独一个方法,方法如下:
private int execUpdate(Query query, Update update,boolean isMany)
{
if (isMany)
{
WriteResult result = template.updateMulti(query, update, Blog.class);
return result.getN();
}
WriteResult result = template.updateFirst(query, update, Blog.class);
return result.getN();
}
该方法可以更新一行或者多行的数据。
1.插入数据
public int insertBlog(Blog blog) {
template.insert(blog);
return 1;
}
2.根据某列更新某列内容;
public int updateContentsForId(String id, String contents) {
Query query=new Query();
query.addCriteria(Criteria.where("_id").is(id));
Update update=new Update();
update.set("contents",contents);
return this.execUpdate(query,update,false);
}
3.添加一列,并给出那列的默认值。
public int addBstatus(String keyName, String defaultValue) {
Update update=new Update();
update.set(keyName,defaultValue);
return this.execUpdate(null,update,true);
}
4.给某个数组添加内容
public int addKeyword(String title, String keyword) {
Query query=new Query();
query.addCriteria(Criteria.where("title").is(title));
Update update=new Update();
update.addToSet("keywords",keyword);
return this.execUpdate(query,update,false);
}
5.添加某个嵌套子文档:
public int addPdetail(String title, Pdetail pdetail) {
Query query=new Query();
query.addCriteria(Criteria.where("title").is(title));
Update update=new Update();
update.push("pdetails",pdetail);
update.inc("pcount",1);
return this.execUpdate(query,update,false);
}
6.更新嵌套子文档中的内容
public int updatePl(String title, String plid, String plcontent, Date pltime) {
Query query=new Query();
query.addCriteria(Criteria.where("title").is(title).and("pdetails.plid").is("2"));
Update update=new Update();
update.set("pdetails.$.plcontent",plcontent);
update.set("pdetails.$.pltime",pltime);
return this.execUpdate(query,update,false);
}
7.删除数组中的第一行
public int deleteFirstPl(String title) {
Query query=new Query();
query.addCriteria(Criteria.where("title").is(title));
Update update=new Update();
update.pop("pdetails",Update.Position.FIRST);
return this.execUpdate(query,update,false);
}
8.删除数组中的最后一行
public int deleteLastPl(String title) {
Query query=new Query();
query.addCriteria(Criteria.where("title").is(title));
Update update=new Update();
update.pop("pdetails",Update.Position.LAST);
return this.execUpdate(query,update,false);
}
9.删除某个嵌套子文档的全部内容。
public int deleteAllPlAndClosePl(String title) {
Query query=new Query();
query.addCriteria(Criteria.where("title").is(title));
Update update=new Update();
Pdetail pdetail=new Pdetail();
update.pull("pdetails",pdetail);
update.set("pstate",0);
return this.execUpdate(query,update,true);
}
10.删除集合
public void dropCollection() {
template.dropCollection(Blog.class);
}
11.删除数据库
public void dropDateBase() {
template.getDb().dropDatabase();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)