Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

เพิ่มเอกสารหลายรายการพร้อมกันด้วย bulkWrite() ใน MongoDB

ใช้ bulkWrite() เพื่อดำเนินการเขียนหลายรายการ (Insert, Update, Delete) ในคำสั่งเดียว ประหยัด Network Round-trips

ตัวอย่างข้อมูลและการเตรียม 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
        }
    });
});

รัน bulkWrite

> db.demo397.bulkWrite(op1);
{
    "acknowledged" : true,
    "deletedCount" : 0,
    "insertedCount" : 0,
    "matchedCount" : 0,
    "upsertedCount" : 2,
    "insertedIds" : {},
    "upsertedIds" : {
        "0" : ObjectId("5e5e8c07f995e1718151981c"),
        "1" : ObjectId("5e5e8c07f995e1718151981d")
    }
}

ตรวจสอบข้อมูลที่เพิ่ม

> db.demo397.find();
{
    "_id" : ObjectId("5e5e8c07f995e1718151981c"),
    "Name" : "John", "Value1" : 100, "Value2" : 200
}
{
    "_id" : ObjectId("5e5e8c07f995e1718151981d"),
    "Name" : "Bob", "Value1" : 100, "Value2" : 200
}

ประเภท Operation ใน bulkWrite:

  • insertOne - เพิ่มเอกสารใหม่
  • updateOne / updateMany - อัปเดต
  • deleteOne / deleteMany - ลบ
  • replaceOne - แทนที่เอกสารทั้งฉบับ

ตัวเลือก: ordered: true (default หยุดถ้า error) หรือ ordered: false (ทำต่อไปแม้ error)