Search code examples
javamongodbmongodb-java

Replacing a mongo doc when a condition is met using mongo java driver 3.0+


I have a requirement in which multiple clients are concurrently writing to a MongoDB. Each Mongo doc is having a custom version field. Also I have to ensure that old doc does not overwrite a new doc. Each write completely replaces a mongo doc.

My Replace document code looks something like below:- (in the example below version let'say can be obtained by 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())
            }

Can some one let me know how can I add the version check?


Solution

  • The below query worked for me:-

    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));
    

    Then while doing the bulkWrite catching MongoBulkWriteException and igonoring error code 11000 & 11001