ใช้ $push ใน update() พร้อม multi: true
เพื่อเพิ่มค่าเข้าไปในอาร์เรย์ของ ทุกเอกสาร ในคอลเลกชัน ให้ใช้ update() พร้อม {multi: true}
สร้างข้อมูลตัวอย่าง
> db.demo747.insertOne({"CountryName":["US","IND"]});
> db.demo747.insertOne({"CountryName":["UK","US"]});
> db.demo747.insertOne({"CountryName":["UK","IND"]});
แสดงข้อมูลก่อน push
> db.demo747.find();
ผลลัพธ์:
{ "_id" : ObjectId("5eae6a50a930c785c834e55f"), "CountryName" : [ "US", "IND" ] }
{ "_id" : ObjectId("5eae6a57a930c785c834e560"), "CountryName" : [ "UK", "US" ] }
{ "_id" : ObjectId("5eae6a60a930c785c834e561"), "CountryName" : [ "UK", "IND" ] }
คิวรี Push "AUS" เข้าไปใน CountryName ของทุกเอกสาร
> db.demo747.update({},{$push:{CountryName:"AUS"}},{multi:true});
ผลลัพธ์: WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
แสดงข้อมูลหลัง push
> db.demo747.find();
ผลลัพธ์: ทุกเอกสารมี "AUS" เพิ่มเข้าไปในอาร์เรย์
{ "_id" : ObjectId("5eae6a50a930c785c834e55f"), "CountryName" : [ "US", "IND", "AUS" ] }
{ "_id" : ObjectId("5eae6a57a930c785c834e560"), "CountryName" : [ "UK", "US", "AUS" ] }
{ "_id" : ObjectId("5eae6a60a930c785c834e561"), "CountryName" : [ "UK", "IND", "AUS" ] }