Not able to update mongo in bulk using updateone with upsert

520 views Asked by At

I am facing a problem. I am trying to update if already exists else insert if not present. I am using Bulk API of spring-mongo driver.

DBCollection dbCollection = mongoTemplate.getCollection("supcInfo");
        BulkWriteOperation bulkWriteOperation = dbCollection.initializeUnorderedBulkOperation();
BulkUpdateRequestBuilder builder = bulkWriteOperation.find(new BasicDBObject("_id", supcInfo.getSupc())).upsert();
BasicDBObject dbObject = new BasicDBObject("$set",new BasicDBObject("_id", supcInfo.getSupc()));
         dbObject = dbObject.append("$set",new BasicDBObject("pogId", supcInfo.getPogId()));
         dbObject = dbObject.append("$set",new BasicDBObject("mrp", supcInfo.getMrp()));
         dbObject = dbObject.append("$set",new BasicDBObject("price", supcInfo.getPrice()));
         dbObject = dbObject.append("$set",new BasicDBObject("primarySellerCode", supcInfo.getPrimarySellerCode()));
         dbObject =  dbObject.append("$set",new BasicDBObject("camsEnabled", supcInfo.isCamsEnabled()));
         dbObject =  dbObject.append("$set",new BasicDBObject("availability", supcInfo.getAvailability()));
         dbObject = dbObject.append("$set",new BasicDBObject("updateTs", supcInfo.getUpdateTs()));
builder.updateOne(dbObject);
bulkWriteOperation.execute();

But all fields are not getting updated. Can any one tell me reason and replaceOne works fine but It will recreate Index if there are any.

1

There are 1 answers

1
s7vr On BEST ANSWER

You don't need the bulk write operations here. You can use the regular update and you should be fine.

Your usage of DBObject is incorrect. You are overwriting the $set key.

BasicDBObject updateFields = new BasicDBObject("pogId", supcInfo.getPogId()).append("mrp", supcInfo.getMrp()); // Rest of fields.
BasicDBObject dbObject = new BasicDBObject("$set",updateFields);