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

เพิ่มค่าใน Nested Object ของ MongoDB ด้วย $inc

ใช้ $inc กับ Positional Operator $

เมื่อต้องเพิ่มค่าในฟิลด์ภายในออบเจกต์ที่อยู่ในอาร์เรย์ ใช้ $inc ร่วมกับ $ (positional operator) เพื่อระบุตำแหน่งที่ match

ตัวอย่าง

สร้างคอลเลกชัน incrementValueDemo:

> db.incrementValueDemo.insertOne({
    "StudentName":"Larry","StudentCountryName":"US",
    "StudentDetails":[{"StudentSubjectName":"Math","StudentMathMarks":79}]
});

เพิ่มคะแนน Math ขึ้น 1

> db.incrementValueDemo.update(
    {"StudentDetails.StudentSubjectName": "Math"},
    {$inc: {"StudentDetails.$.StudentMathMarks": 1}}
);

ผลลัพธ์:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ตรวจสอบค่าหลังเพิ่ม

> db.incrementValueDemo.find().pretty();

ผลลัพธ์:

{ 
    "_id" : ObjectId("..."), 
    "StudentName" : "Larry", 
    "StudentCountryName" : "US", 
    "StudentDetails" : [
        {"StudentSubjectName" : "Math", "StudentMathMarks" : 80}
    ] 
}

$ จะอ้างอิงถึงอิลิเมนต์แรกในอาร์เรย์ที่ match เงื่อนไขใน query