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

MongoDB $push เพิ่ม Document เข้า Array (Embedded Document)

Operator $push ร่วมกับ update() ใช้เพิ่ม Document ใหม่เข้าไปใน Array ของ Embedded Documents เนื้อหานี้สาธิตการเพิ่มรายการวิชาใหม่ใน Array details

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

> db.demo310.insertOne({
  "Name":"Chris",
  "details":[
    {"Id":101,"Subject":"MySQL"},
    {"Id":102,"Subject":"MongoDB"}
  ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e50cabdf8647eb59e562043") }

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

> db.demo310.find();
{
  "_id" : ObjectId("5e50cabdf8647eb59e562043"),
  "Name" : "Chris",
  "details" : [
    { "Id" : 101, "Subject" : "MySQL" },
    { "Id" : 102, "Subject" : "MongoDB" }
  ]
}

Query $push เพิ่ม Document ใหม่

> db.demo310.update(
  { _id: ObjectId("5e50cabdf8647eb59e562043") },
  { $push: { "details": { "Id": 103, "Subject": "Java" } } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ผลลัพธ์หลังเพิ่ม

> db.demo310.find();
{
  "_id" : ObjectId("5e50cabdf8647eb59e562043"),
  "Name" : "Chris",
  "details" : [
    { "Id" : 101, "Subject" : "MySQL" },
    { "Id" : 102, "Subject" : "MongoDB" },
    { "Id" : 103, "Subject" : "Java" }
  ]
}

ตัวเลือก $push เพิ่มเติม

  • $each: เพิ่มหลาย Element พร้อมกัน
    { $push: { details: { $each: [ {Id:104, Subject:"Python"}, {Id:105, Subject:"Go"} ] } } }
  • $slice: จำกัดขนาด Array (เก็บแค่ N ตัวล่าสุด)
    { $push: { details: { $each: [...], $slice: -5 } } }
  • $sort: เรียง Array หลัง Push
    { $push: { details: { $each: [...], $sort: { Id: 1 } } } }
  • $position: ระบุตำแหน่งที่จะ Insert (Default = ท้าย)
    { $push: { details: { $each: [...], $position: 0 } } }
  • MongoDB 3.2+ ใช้ updateOne() แทน update()