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

การใช้ $push เพิ่มข้อมูลใน Embedded Document Array ของ MongoDB

Operator $push ใน MongoDB ใช้สำหรับเพิ่ม Element ใหม่เข้าไปใน Array โดยเฉพาะ Embedded Document Array (Array ที่เก็บ Object) เนื้อหานี้สาธิตการเพิ่มรายการใหม่ในฟิลด์ details ซึ่งเป็น Array ของ Object

ตัวอย่างข้อมูลทดสอบ

> db.demo288.insertOne({"Name":"Chris",details:[{"CountryName":"US","Marks":78},{"CountryName":"UK","Marks":68}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4c0393f49383b52759cbbe") }

แสดงข้อมูลเดิม

> db.demo288.find();
{
  "_id" : ObjectId("5e4c0393f49383b52759cbbe"),
  "Name" : "Chris",
  "details" : [
    { "CountryName" : "US", "Marks" : 78 },
    { "CountryName" : "UK", "Marks" : 68 }
  ]
}

Query เพิ่มข้อมูลด้วย $push

> db.demo288.update(
  {Name: "Chris"},
  {$push:{ "details":{"CountryName" : "AUS", "Marks" : 98} }},
  {upsert:true}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ผลลัพธ์หลังอัปเดต

> db.demo288.find();
{
  "_id" : ObjectId("5e4c0393f49383b52759cbbe"),
  "Name" : "Chris",
  "details" : [
    { "CountryName" : "US", "Marks" : 78 },
    { "CountryName" : "UK", "Marks" : 68 },
    { "CountryName" : "AUS", "Marks" : 98 }
  ]
}

จุดสำคัญ

  • $push เพิ่ม Element เข้าไปท้าย Array
  • upsert: true จะสร้างเอกสารใหม่หากไม่พบเอกสารที่ Match
  • ใช้ Dot Notation (details) ระบุ Path ของ Array ที่ต้องการเพิ่ม
  • ใน MongoDB เวอร์ชันใหม่ แนะนำให้ใช้ updateOne() หรือ updateMany() แทน update()