使用 mongo java 驱动程序 3.0+ 满足条件时替换 mongo 文档
Replacing a mongo doc when a condition is met using mongo java driver 3.0+
我有一个要求,其中多个客户端同时写入一个 MongoDB。每个 Mongo 文档都有一个自定义 version
字段。我还必须确保旧文档不会覆盖新文档。每次写入完全替换 mongo 文档。
我的替换文档代码如下所示:-(在下面的示例中 version
假设可以通过 doc.getVersion()
获得):-
MongoCollection<Document> productCollection = mongoDb.getCollection("test");
List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
for (MongoInputDoc doc : docCollection) {
UpdateOptions updateOptions = new UpdateOptions();
updateOptions.upsert(true);
writes.add(new ReplaceOneModel<Document>(new Document(doc.getIdName(), new BsonString(doc.getIdValue())),
doc.getDoc(), updateOptions));
}
try {
if (writes.size() > 0) {
productCollection.bulkWrite(writes);
}
} catch (Exception e) {
System.out.println(e.getMessage())
}
谁能告诉我如何添加版本检查?
以下查询对我有用:-
Document query = new Document("$and", Arrays.asList(new Document(
doc.getIdName(), new BsonString(doc.getIdValue())),
new Document("doc_version", new Document("$lt",
doc.getVersion()))));
writes.add(new ReplaceOneModel<Document>(query, doc.getDoc(),
updateOptions));
然后在执行 bulkWrite 时捕获 MongoBulkWriteException
并忽略错误代码 11000
& 11001
我有一个要求,其中多个客户端同时写入一个 MongoDB。每个 Mongo 文档都有一个自定义 version
字段。我还必须确保旧文档不会覆盖新文档。每次写入完全替换 mongo 文档。
我的替换文档代码如下所示:-(在下面的示例中 version
假设可以通过 doc.getVersion()
获得):-
MongoCollection<Document> productCollection = mongoDb.getCollection("test");
List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
for (MongoInputDoc doc : docCollection) {
UpdateOptions updateOptions = new UpdateOptions();
updateOptions.upsert(true);
writes.add(new ReplaceOneModel<Document>(new Document(doc.getIdName(), new BsonString(doc.getIdValue())),
doc.getDoc(), updateOptions));
}
try {
if (writes.size() > 0) {
productCollection.bulkWrite(writes);
}
} catch (Exception e) {
System.out.println(e.getMessage())
}
谁能告诉我如何添加版本检查?
以下查询对我有用:-
Document query = new Document("$and", Arrays.asList(new Document(
doc.getIdName(), new BsonString(doc.getIdValue())),
new Document("doc_version", new Document("$lt",
doc.getVersion()))));
writes.add(new ReplaceOneModel<Document>(query, doc.getDoc(),
updateOptions));
然后在执行 bulkWrite 时捕获 MongoBulkWriteException
并忽略错误代码 11000
& 11001