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

Cập nhật nhiều bản ghi với một truy vấn trong MongoDB (bulkWrite)

Sử dụng bulkWrite() để thực hiện nhiều thao tác viết cùng lúc

bulkWrite() cho phép gửi nhiều lệnh insertOne, updateOne, updateMany, deleteOne, deleteMany, replaceOne trong một lần gọi mạng, tối ưu hiệu năng.

Dữ liệu mẫu

> db.demo760.insertMany([
  { id: 1, details: { Value1: 100, Value2: 50 } },
  { id: 2, details: { Value1: 60, Value2: 70 } },
  { id: 3, details: { Value1: 80, Value2: 90 } }
]);

Truy vấn bulkWrite: cập nhật id=1 và id=2

db.demo760.bulkWrite([
  {
    updateOne: {
      filter: { id: 1 },
      update: { $set: { 'details.Value1': 900, 'details.Value2': 500 } }
    }
  },
  {
    updateOne: {
      filter: { id: 2 },
      update: { $set: { 'details.Value1': 1000, 'details.Value2': 2000 } }
    }
  }
]);

Kết quả

{ "_id": ObjectId("..."), "id": 1, "details": { "Value1": 900, "Value2": 500 } }
{ "_id": ObjectId("..."), "id": 2, "details": { "Value1": 1000, "Value2": 2000 } }
{ "_id": ObjectId("..."), "id": 3, "details": { "Value1": 80, "Value2": 90 } }  // Không thay đổi

Hai bản ghi được cập nhật trong một lệnh, bản ghi id=3 giữ nguyên.