ใช้แนวคิดของ initializeUnorderedBulkOp() ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"John","CustomerPurchaseAmount":500}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb06d78f205348bc626") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Chris","CustomerPurchaseAmount":700}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb26d78f205348bc627") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"David","CustomerPurchaseAmount":50}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb36d78f205348bc628") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Larry","CustomerPurchaseAmount":1900}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb46d78f205348bc629") }
ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.upDateMultipleRowsDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5cd6ceb06d78f205348bc626"), "CustomerName" : "John", "CustomerPurchaseAmount" : 500 } { "_id" : ObjectId("5cd6ceb26d78f205348bc627"), "CustomerName" : "Chris", "CustomerPurchaseAmount" : 700 } { "_id" : ObjectId("5cd6ceb36d78f205348bc628"), "CustomerName" : "David", "CustomerPurchaseAmount" : 50 } { "_id" : ObjectId("5cd6ceb46d78f205348bc629"), "CustomerName" : "Larry", "CustomerPurchaseAmount" : 1900 }
ต่อไปนี้เป็นแบบสอบถามเพื่ออัปเดตหลายแถวในแบบสอบถามเดียว -
> var manyUpdateValue = db.upDateMultipleRowsDemo.initializeUnorderedBulkOp(); > manyUpdateValue.find({ _id: ObjectId("5cd6ceb06d78f205348bc626")}).updateOne({$set:{"CustomerName":"Bob" }}); > manyUpdateValue.find({ _id: ObjectId("5cd6ceb36d78f205348bc628")}).updateOne({$set:{"CustomerPurchaseAmount":56544444}}); > manyUpdateValue.execute(); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 2, "nModified" : 2, "nRemoved" : 0, "upserted" : [ ] })
ให้เราตรวจสอบเอกสารทั้งหมดอีกครั้ง -
> db.upDateMultipleRowsDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5cd6ceb06d78f205348bc626"), "CustomerName" : "Bob", "CustomerPurchaseAmount" : 500 } { "_id" : ObjectId("5cd6ceb26d78f205348bc627"), "CustomerName" : "Chris", "CustomerPurchaseAmount" : 700 } { "_id" : ObjectId("5cd6ceb36d78f205348bc628"), "CustomerName" : "David", "CustomerPurchaseAmount" : 56544444 } { "_id" : ObjectId("5cd6ceb46d78f205348bc629"), "CustomerName" : "Larry", "CustomerPurchaseAmount" : 1900 }