Search code examples
mongodbmongo-javamongo-java-driver

Unordered bulk update in MongoDB using JAVA


I have MongoDB documents like:

{_id:1001, "title":"abc", "author":"xyz"}

What is the best way to update author for 1 million such documents? I came to know about the unordered bulk update in MongoDB. How to implement that using Mongo's Java Driver.


Solution

  •     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"));
        //append all other documents 
        builder.execute();