Search code examples
mongodbspring-data-mongodbbatch-insert

springdata MongoDB batch inserts with continueOnError option


MongoDB supports a continueOnError option so that batch insert continues even if there is a failure in a single document insertion.

Is there a way to achieve this using spring-data version 1.3.3.RELEASE. I am using the MongoOperations class and I don't see an API that allows me to do this.

Thanks!!


Solution

  • You should set this through the writeConcern options for MongoTemplate

    mongoTemplate.setWriteConcern( 
        new WriteConcern(<Your options>).continueOnErrorForInsert(true));
    

    Alternately there should be a constructor for for WriteConcern that does this as well.

    More specifically as a usage, I set a Bean in a config class:

    public @Bean
    MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
    
        WriteConcern writeConcern = new WriteConcern(2);
        writeConcern.continueOnErrorForInsert(true);
    
        mongoTemplate.setWriteConcern(writeConcern);
    
        return mongoTemplate;
    }
    

    And then later on, set up the operations:

        MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
    
        Collection collection = new Collection() { ... }
    
        mongoOperation.insert(collection,"collection");   // Uses the writeConcern options