MongoDB中的并发读/写

时间:2016-10-05 09:23:25

标签: java mongodb concurrency jvm locking

我有一个集合,我从中获得最大ID,同时使用max id + 1插入.id列在此集合中是唯一的。

当调用此服务的多个实例时,并发应用程序将读取相同的集合并获取最大ID。但是,由于访问了相同的集合,同一个最大ID被返回到多个实例,我可以在读取该集合中的数据时获得对集合的显式锁定,并在写入Mongo DB后释放锁定吗?

2 个答案:

答案 0 :(得分:1)

使用mongoDB方法collections.findAndModify(),您可以创建自己的" get-and-increment"查询。

例如:

db.collection_name.findAndModify({
  query: { document_identifier: "doc_id_1" },
  update: { $inc: { max_id: 1 } },
  new: true  //return the document AFTER it's updated
})

https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/

请查看此页面以获取更多帮助:

https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

答案 1 :(得分:0)

尝试这种方法

而不是让max id读取集合并将其增加为max id + 1

读取多个实例时,只需提供文档/集合,并在更新时遵循以下逻辑

Let us have the below part in a synchronized block, so that no two threads gets the same max id
synchronize() {
  getMaxId from collection
  increase it by 1
  insert the new document
}

请参阅:

https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/

https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

希望它有帮助!