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

การจัดการ Sub-document ใน MongoDB ด้วย Dot Notation

ใช้ Dot Notation ร่วมกับ Positional Operator $ และ Operator ต่างๆ ($inc, $set ฯลฯ) เพื่ออัปเดต Sub-document ในอาร์เรย์

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

> db.demo378.insertOne({
    Name: 'Chris',
    details: [
        {id:101, Score:56},
        {id:102, Score:78}
    ]
});

แสดงข้อมูลก่อน

> db.demo378.find();
{
    "_id" : ObjectId("5e5a758a2ae06a1609a00b0f"),
    "Name" : "Chris",
    "details" : [ {"id" : 101, "Score" : 56}, {"id" : 102, "Score" : 78} ]
}

คำสั่งลด Score ของ id=102 ลง 8

> db.demo378.update(
    {Name: "Chris", "details.id":102},
    {$inc: {"details.$.Score": -8}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ผลลัพธ์ (Score ของ id 102 เหลือ 70)

> db.demo378.find();
{
    "_id" : ObjectId("5e5a758a2ae06a1609a00b0f"),
    "Name" : "Chris",
    "details" : [ {"id" : 101, "Score" : 56}, {"id" : 102, "Score" : 70} ]
}

คำอธิบาย:

  • Query {Name: "Chris", "details.id":102} หาเอกสารที่ Name=Chris และ details มี id=102
  • details.$.Score ใช้ $ อ้างอิงตำแหน่งของ details ที่ id=102
  • $inc เพิ่ม/ลดค่า (ลบ 8 = เพิ่ม -8)