0

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.

Dev
  • 13,492
  • 19
  • 81
  • 174
  • The bulk operations are used to buffer write operations it client side and execute these in batches. In order to achieve what you want, issue an update comment `db.books.update({auther : "xyz"},{$set : {author: "whatever"}}, {multi:true})` – Ori Dar May 21 '15 at 10:42
  • don't you think a bulk operation is faster in this case? – Dev May 21 '15 at 10:46
  • Well, I don't see any added value if merely want to update a single field for a bunch of documents – Ori Dar May 21 '15 at 10:51

1 Answers1

1
    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();
Dev
  • 13,492
  • 19
  • 81
  • 174