我有一个集合,在使用max id + 1插入时,我将从中获得最大id。id列在这个集合中是唯一的。
当调用此服务的多个实例时,并发应用程序读取相同的集合并获取最大id。但是,由于相同的集合被访问,相同的max id返回到多个实例,所以在读取该集合中的数据时,我是否可以获得该集合的显式锁,并在用Mongo编写后释放锁?
发布于 2016-10-05 11:01:17
使用mongoDB方法collections.findAndModify(),您可以创建自己的“获取和增量”查询。
例如:
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/
请查看此页面以获得更多帮助:
发布于 2016-10-05 11:01:50
试试这种方法
而不是让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://stackoverflow.com/questions/39870129
复制相似问题