MongoDB在Java中的更新数据操作

假如已经存储了document,现在想往document中添加一个description属性,可以这样更新:

Mongo mongo = new Mongo(this.host, this.port);
GridFS fs = new GridFS(mongo.getDB(“database”));
GridFSDBFile file = fs.find(new ObjectId(document.getId()));
file.put(“description”, document.getDescription());
file.save();

也可以使用DBCollection的update方法更新,代码如下:

DBObject queryCondition=new BasicDBObject();
queryCondition.put(“_id”, document.getId());

Mongo mongo = new Mongo(this.host, this.port);
DB db = mongo.getDB(“database”)
DBCollection c = db.getCollection(“fs.files”);

DBObject updatedValue=new BasicDBObject();
updatedValue.put(“description”, document.getDescription());
DBObject updateSetValue=new BasicDBObject(“$set”,updatedValue);
/**
* update document set description=”description” where id=’id’
* updateCondition:更新条件
* updateSetValue:设置的新值
*/
c.update(updateSetValue, updateSetValue);

关于MongoDB的更多资料请查看:

官网:http://www.mongodb.org
Doc Index: www.mongodb.org/display/DOCS/Doc+Index

arthinking wechat
欢迎关注itzhai公众号