Mongo DB更新整个文档和增量版本

时间:2015-08-06 10:53:09

标签: mongodb

我正在尝试使用MongoDB来实现一个JSON文档存储,它使用乐观锁定来处理并发更新。

要实现乐观锁定,我已在文档中添加了_version属性;这跟踪文档更新的次数。调用者将传入他们已修改的文档的_version。如果_version与当前数据库版本不匹配,则会出错。

更新_version以及我使用findAndModify方法的文档。

/* Get JSON into a DBObject
 - remove _version as we can't increment and set it at the same time 
*/
val content = JSON.parse( json ).asInstanceOf[DBObject].remove("_version")

// Query to find the expected current version of the document
val query = BasicDBObjectBuilder.start("_id", myId).append("_version", versionNo).get()

// Update object - set the content and increment the version counter
val update = BasicDBObjectBuilder.start("$set", content).append("$inc",  BasicDBObjectBuilder.start("$version", 1).get()).get()

/* Update the document, 
   increment the version 
   and return the updated document, 
   if the document does not exist then create a new one

   Params: Query, Fields, Sort, Remove, Update, Return New, Upsert
*/
val updatedDBObj = db.getCollection( myCollection ).findAndModify( query, null, null, false, doc, true, true )

这非常有效,但$set只会添加/更新值,并且不会删除已从文档中删除的键。

有没有办法替换整个文档,以便在单个数据库操作中增加版本号?我并不特别热衷于必须对文档进行区分,以确定要添加$set的内容以及删除$unset的内容。

0 个答案:

没有答案