【发布时间】:2015-10-23 09:31:06
【问题描述】:
我开始在工作中使用 MongoDB(使用 spring-data-mongo),所以一切都很好。 但我想知道 MongoDB 如何处理发生的更新?更具体地说,处理这些问题的最佳做法是什么?
例如,我有一个包含地图的文档
@Document(collection = "test)
public class Test {
private String name;
private Map<Long, Holder> myMap;
}
public class Holder {
private List<Integer> list;
}
{
"name": "test",
"myMap: "{"1":"{"list":[1,2,3]}", "2":"{"list":[1,2,3]}"}"
}
Thread A: retrieves the Test Document
Thread A: gets myMap and add a new entry in the list for key "1"
Thread B: retrieves the Test Document
Thread B: gets myMap and add a new entry in the list for key "1"
Thread B: saves the Test Document
Thread A: saves the Test Document
问题是 myMap 中的内容是什么? B 或 A 添加的条目?还是两者都有?
【问题讨论】:
-
这取决于使用的底层 MongoDB 命令,update() 或 findAndModify()。
-
在这种情况下(我使用的是spring存储库)repository.findOne(id) ... repository.save(document);
-
我不确定
repository.save()的内部结构。要对更新操作进行更精细的控制,您必须查看methods for the Update class,或使用findAndModify()的原子更新。 -
假设我正在使用 findAndModify(),有没有办法在 myMap 中“添加”(而不是完全替换)一个条目?
标签: mongodb dictionary collections concurrency updates