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

ทำ multiple updates ด้วย bulk operations และอัปเดตอิลิเมนต์ในอาร์เรย์ใน MongoDB


สำหรับเรื่องนี้ ให้ใช้ initializeOrderedBulkOp() มันจะ initialize และคืนค่า Bulk() operations builder ใหม่สำหรับคอลเลกชัน Builder จะสร้าง ordered list ของ write operations ที่ MongoDB จะ execute แบบ bulk มาสร้างคอลเลกชันพร้อมเอกสารกันก่อน

>db.demo550.insertOne({"Name":"Chris","details":[{"Marks":49,Result:"fail"},{"Marks":58,Result:"fail"}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e8e35bd9e5f92834d7f05e4") }

แสดงเอกสารทั้งหมดจากคอลเลกชันด้วยเมธอด find()

> db.demo550.find();

จะได้ผลลัพธ์ดังนี้

{ "_id" : ObjectId("5e8e35bd9e5f92834d7f05e4"), "Name" : "Chris", "details" : [ { "Marks" : 49, "Result" : "fail" }, { "Marks" : 58, "Result" : "fail" } ] }

คำสั่งสำหรับอัปเดตอิลิเมนต์ในอาร์เรย์ใน MongoDB และทำ bulk operations

> var all= db.demo550.initializeOrderedBulkOp(), ... itr = 0; > db.demo550.find({ "Name": "Chris", "details.Result": "fail" }).forEach(function(doc) { ...    doc.details.filter(function(d){ return d.Result = "fail" }).forEach(function(d) { ...       all.find({ "_id": doc._id, "details.Result": "fail" }).updateOne({ ...          "$set": { "details.$.Result": "PASS" } ...       }); ...       itr++; ...       if ( itr % 10== 0 ) { ...          all.execute(); ...          all = db.demo550.initializeOrderedBulkOp(); ...       } ...    }); ...    if ( itr % 10 != 0 ) ...    all.execute(); ... });

แสดงเอกสารทั้งหมดจากคอลเลกชันด้วยเมธอด find()

> db.demo550.find();

จะได้ผลลัพธ์ดังนี้

{ "_id" : ObjectId("5e8e35bd9e5f92834d7f05e4"), "Name" : "Chris", "details" : [ { "Marks" : 49, "Result" : "PASS" }, { "Marks" : 58, "Result" : "PASS" } ] }