Upserting a collection of objects in Mongo in a batch in java using Mongotemplate

48 Views Asked by At

I have a list of objects of type MyObject, and I wish to insert an object if its not present in the mongo collection, or update if it does.

MyObject contains multiple fields, but I want to update if fields f1 & f2 are present in the mongo collection, and insert otherwise.

I know that I can do this for a single object using MongoTemplate's upsert method, and can insert a bunch of objects using MongoTemplate's insertAll method, but neither does what I'm trying to do.

What's the best and most efficient way to achieve what I'm trying to do?

1

There are 1 best solutions below

0
On BEST ANSWER
 public <T> void batchUpdate(String collectionName, List<T> documents, Class<T> tClass) {
    BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, tClass, collectionName);
    for (T document : documents) {
        Document doc = new Document();
        mongoTemplate.getConverter().write(document, doc);
        org.springframework.data.mongodb.core.query.Query  query = new org.springframework
                .data.mongodb.core.query.Query(Criteria.where(UNDERSCORE_ID).is(doc.get(UNDERSCORE_ID)));
        Document updateDoc = new Document();
        updateDoc.append("$set", doc);
        Update update = Update.fromDocument(updateDoc, UNDERSCORE_ID);
        bulkOps.upsert(query, update);
    }
    bulkOps.execute();
}

You can use this code as a reference and modify it based on your requirement of fields to be checked.

You can check the Mongo doc for Bulk.find.update() here :- https://www.mongodb.com/docs/manual/reference/method/Bulk.find.update/