【问题标题】:Replacing a mongo doc when a condition is met using mongo java driver 3.0+使用 mongo java driver 3.0+ 满足条件时替换 mongo doc
【发布时间】:2015-12-28 15:52:51
【问题描述】:

我有多个客户端同时写入 MongoDB 的要求。每个 Mongo 文档都有一个自定义的 version 字段。此外,我必须确保旧文档不会覆盖新文档。每次写入都完全替换了一个 mongo 文档。

我的替换文档代码如下所示:-(在下面的示例中 version let'say 可以通过 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())
            }

谁能告诉我如何添加版本检查?

【问题讨论】:

    标签: java mongodb mongodb-java


    【解决方案1】:

    以下查询对我有用:-

    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

    【讨论】:

      猜你喜欢
      • 2015-11-12
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2019-05-21
      • 1970-01-01
      • 2018-08-24
      相关资源
      最近更新 更多