Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cập nhật hàng loạt tài liệu từ danh sách cặp key-value trong MongoDB

Tạo collection với dữ liệu ban đầu:

> db.demo227.insertOne({"_id":"101","Name":"Chris"});
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo227.insertOne({"_id":"102","Name":"Bob"});
{ "acknowledged" : true, "insertedId" : "102" }

Hiển thị dữ liệu:

> db.demo227.find();
{ "_id" : "101", "Name" : "Chris" }
{ "_id" : "102", "Name" : "Bob" }

Sử dụng initializeUnorderedBulkOp() để cập nhật hàng loạt:

> var bulkUpdateValue = [{"_id": "101", "Name": "Robert"}, {"_id": "102", "Name": "Sam"}];
> var bulkUpdate = db.demo227.initializeUnorderedBulkOp();
> for (var i = 0; i < bulkUpdateValue.length; i++) {
...   var updateCounter = bulkUpdateValue[i];
...   bulkUpdate.find({_id: updateCounter._id}).update({$set: {Name: updateCounter.Name}});
... }
> bulkUpdate.execute();
BulkWriteResult({
  "writeErrors" : [ ],
  "writeConcernErrors" : [ ],
  "nInserted" : 0,
  "nUpserted" : 0,
  "nMatched" : 2,
  "nModified" : 2,
  "nRemoved" : 0,
  "upserted" : [ ]
})

Kết quả sau cập nhật:

> db.demo227.find();
{ "_id" : "101", "Name" : "Robert" }
{ "_id" : "102", "Name" : "Sam" }