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

Thêm nhiều tài liệu cùng lúc trong MongoDB với bulkWrite

Sử dụng bulkWrite() để thực hiện nhiều thao tác ghi (insert, update, delete) trong một lệnh duy nhất, hiệu quả hơn nhiều so với gọi riêng lẻ.

Tạo mảng dữ liệu và xây dựng operations:

> const arrayList = [
  {"Value1":100, "Value2":200, "Name": "John"},
  {"Value1":100, "Value2":200, "Name": "Bob"}
];
> let op1 = [];
> arrayList.forEach(({ Value1, Value2, Name }) => {
  op1.push({
    "updateOne": {
      "filter": { Name },
      "update": { "$set": { Value1, Value2, Name } },
      "upsert": true
    }
  });
});
> db.demo397.bulkWrite(op1);
{ "acknowledged" : true, "deletedCount" : 0, "insertedCount" : 0, "matchedCount" : 0, "upsertedCount" : 2, "insertedIds" : { "0" : ObjectId("5e5e8c07f995e1718151981c"), "1" : ObjectId("5e5e8c07f995e1718151981d") }, "upsertedIds" : { "0" : ObjectId("5e5e8c07f995e1718151981c"), "1" : ObjectId("5e5e8c07f995e1718151981d") } }

Kết quả (2 tài liệu mới được upsert):

> db.demo397.find();

Các loại operation trong bulkWrite:

  • insertOne: chèn mới
  • updateOne / updateMany: cập nhật
  • replaceOne: thay thế toàn bộ
  • deleteOne / deleteMany: xóa

Tùy chọn quan trọng:

  • ordered: true (mặc định): dừng lại khi lỗi
  • ordered: false: tiếp tục các operation còn lại dù có lỗi (unordered bulk)
  • upsert: true: tạo mới nếu không tìm thấy

Lợi ích: Giảm network round-trip, atomic ở mức operation đơn lẻ, hiệu năng cao cho batch processing.