How to perform a bulk update of documents in MongoDB with Java?

Viewed 51868

I'm using MongoDB 3.2 and MongoDB Java Driver 3.2. I have an array of a couple of hundreds of updated documents which should be now saved/stored in MongoDB. In order to do that, I iterate over the array and call for each document in this array the updateOne() method.

Now, I want to re-implement this logic with a bulk update. I tried to find an example of bulk update in MongoDB 3.2 with MongoDB Java Driver 3.2.

I tried this code:

MongoClient mongo = new MongoClient("localhost", 27017);

DB db = (DB) mongo.getDB("test1");
DBCollection collection = db.getCollection("collection");
BulkWriteOperation builder = collection.initializeUnorderedBulkOperation();

builder.find(new BasicDBObject("_id", 1001)).upsert()
    .replaceOne(new BasicDBObject("_id", 1001).append("author", "newName"));

builder.execute();

But it seems that this approach is based on an outdated MongoDB Java Driver, such as 2.4 and uses deprecated methods.

My question:
How to perform a bulk update of documents in MongoDB 3.2 with MongoDB Java Driver 3.2?

1 Answers
Related