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

MongoDB concurrent update กับซับคอลเลกชัน


สำหรับการอัปเดต ให้ใช้ update() ธรรมดา ใช้โอเปอเรเตอร์ $push เพื่อเพิ่มค่าที่ระบุ และใช้สัญลักษณ์จุด (dot notation) เพื่อเข้าถึงซับคอลเลกชันและอัปเดตภายใน update()

มาสร้างคอลเลกชันพร้อมเอกสารกันก่อน

> db.demo547.insertOne( ... { ...    Name : "Chris", ...    Test : ...    { ...       "FirstTest" : ...       { ...          Scores: [56,29,76] ...       }, ...       "SecondTest" : ...       { ...          Scores: [98,91,78] ...       } ...    } ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e8e2d579e5f92834d7f05dd") }

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

> db.demo547.find();

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

{ "_id" : ObjectId("5e8e2d579e5f92834d7f05dd"), "Name" : "Chris", "Test" : { "FirstTest" : { "Scores" : [ 56, 29, 76 ] }, "SecondTest" : { "Scores" : [ 98, 91, 78 ] } } }

คำสั่งสำหรับ concurrent update กับซับคอลเลกชัน

> db.demo547.update({"Name":"Chris"}, { $push:{ "Test.FirstTest.Scores" : 99}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo547.find();

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

{ "_id" : ObjectId("5e8e2d579e5f92834d7f05dd"), "Name" : "Chris", "Test" : { "FirstTest" : { "Scores" : [ 56, 29, 76, 99 ] }, "SecondTest" : { "Scores" : [ 98, 91, 78 ] } } }