Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Exception when bulkwrite with ordered as false in MongoDB java

I am using the Mongo DB java driver:

collection.bulkWrite(documents);

I have 1 million records to be inserted. If the insertion of one of the records fails then on the first failure the remaining records won't get inserted. In order to avoid this I found that there are BulkWriteOptions with ordered as false;

collection.bulkWrite(documents, new BulkWriteOptions().ordered(false) )

If any exception occurs during the above operation, can we get the list of the records for which bulkwrite failed and can we try inserting those records again?

like image 486
svs teja Avatar asked Sep 13 '25 12:09

svs teja


1 Answers

I think you're looking for something similar..

BulkWriteOptions bulkWriteOptions = new BulkWriteOptions();
bulkWriteOptions.ordered(true);

BulkWriteResult bulkWriteResult = null;
try {
    bulkWriteResult = mongoCollection.bulkWrite(updateDocuments,
            bulkWriteOptions);
} catch (BulkWriteException e) {
    List<BulkWriteError> bulkWriteErrors = e.getWriteErrors();
    for (BulkWriteError bulkWriteError : bulkWriteErrors) {
        int failedIndex = bulkWriteError.getIndex();
        Long failedEntity = entityList.get(failedIndex);
        System.out.println("Failed record: " + failedEntity);
        //handle rollback
    }
}
like image 91
Ashutosh Srivastav Avatar answered Sep 15 '25 10:09

Ashutosh Srivastav