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

วิธีเพิ่มรายการใหม่เข้าไปในอาร์เรย์ภายในออบเจกต์ใน MongoDB

ใช้ตัวดำเนินการ $elemMatch ร่วมกับ $push เพื่อเพิ่มรายการเข้าไปในอาร์เรย์ที่อยู่ภายในออบเจกต์ เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.pushNewItemsDemo.insertOne(
  {
    "_id" : 1,
    "StudentScore" : 56,
    "StudentOtherDetails" : [
      {
        "StudentName" : "John",
        "StudentFriendName" : [
          "Bob",
          "Carol"
        ]
      },
      {
        "StudentName" : "David",
        "StudentFriendName" : [
          "Mike",
          "Sam"
        ]
      }
    ]
  }
);
{ "acknowledged" : true, "insertedId" : 1 }

แสดงเอกสารทั้งหมด:

> db.pushNewItemsDemo.find();
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] }

คิวรี่เพิ่ม "James" เข้าไปใน StudentFriendName ของนักเรียนชื่อ David:

> db.pushNewItemsDemo.update(
  {"_id":1, "StudentOtherDetails":{"$elemMatch":{"StudentName":"David"}}},
  {"$push":{"StudentOtherDetails.$.StudentFriendName":"James"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ตรวจสอบเอกสารอีกครั้ง:

> db.pushNewItemsDemo.find();
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam", "James" ] } ] }

คำอธิบาย: $elemMatch ใช้จับคู่ออบเจกต์ภายในอาร์เรย์ StudentOtherDetails ที่มี StudentName เป็น "David" จากนั้น $push พร้อมตัวระบุตำแหน่ง $. (positional operator) จะเพิ่มค่าเข้าไปในอาร์เรย์ StudentFriendName ของออบเจกต์ที่จับคู่ได้เท่านั้น