2015-12-28 45 views
1

我有一個要求,即多個客戶端正在同時寫入MongoDB。每個Mongo文檔都有自定義的version字段。此外,我必須確保舊文檔不會覆蓋新文檔。每個寫入都完全取代了mongo文檔。當使用mongo java驅動程序滿足條件時替換mongo文檔3.0+

我替換文件的代碼看起來象下面這樣: - (在下面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()) 
      } 

有一個人可以讓我知道我怎麼可以添加版本檢查?

回答

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和igonoring錯誤代碼11000 & 11001

相關問題