Search code examples
mongodbspring-data-mongodbmongo-java-drivermongo-java

Java - Insert/Update with MongoDB collection bulkWrite


I am very new to MongoDB. Trying to understand the best option to perform Bulk Write in MongoDB. I want to periodically refresh my Application collection. The key's for documents are AppID, AppName and AppStatus. Below are the actions I want to perform in every run -

  1. Find the AppID in Application collection.
  2. If not exists, perform an insert
  3. If exists, only update the value of AppStatus key.
List<Application> applist = getAppList(); // List contains All the Application

private final MongoClient mongoClient;

private final MongoTemplate mongoTemplate;

MongoCollection<Document> collection =
                  mongoTemplate.getDb().getCollection("Application");
collection.bulkWrite (????);

How do I loop over the appList and perform a bulk insert/update ?


Solution

  • You can use org.springframework.data.mongodb.core.BulkOperations to perform bulk update/insert/upsert/delete operations.

    List<Application> applist = getAppList();
    
    List<Pair<Query, Update>> updates = new ArrayList<>(applist.size());
    applist.forEach(application -> {
        Query query = Query.query(Criteria.where("AppID").is(application.getAppID()));
    
        Update update = new Update();
        update.set("AppID", application.getAppID());
        update.set("AppName", application.getAppName());
        update.set("AppStatus", application.getAppStatus());
    
        updates.add(Pair.of(query, update));
    });
    
    BulkOperations bulkOperations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, "Application");
    bulkOperations.upsert(updates);
    bulkOperations.execute();