ใช้ Positional Notation (Dot Notation) อัปเดทค่าที่ Index เฉพาะ
ใน MongoDB สามารถอัปเดทค่าในอาร์เรย์ที่ Index เฉพาะได้โดยใช้ Dot Notation: arrayName.index.fieldName
ตัวอย่างข้อมูล: อาร์เรย์ 2 มิติ (Nested Array)
> db.updateObjectDemo.insertOne({
id: 101,
"StudentDetails": [
[ { "StudentName": "John" }, { "StudentName": "Chris" } ],
[ { "StudentName": "Carol" }, { "StudentName": "David" } ]
]
});
โครงสร้างข้อมูล
StudentDetails[0][0] = { StudentName: "John" }
StudentDetails[0][1] = { StudentName: "Chris" }
StudentDetails[1][0] = { StudentName: "Carol" }
StudentDetails[1][1] = { StudentName: "David" } ← จะแก้ค่านี้
คำสั่งอัปเดท Index [1][1] ให้เป็น "Mike"
> db.updateObjectDemo.update(
{ "id": 101 },
{ $set: { "StudentDetails.1.1.StudentName": "Mike" } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
ผลลัพธ์
> db.updateObjectDemo.find().pretty();
{
"StudentDetails" : [
[ { "StudentName" : "John" }, { "StudentName" : "Chris" } ],
[ { "StudentName" : "Carol" }, { "StudentName" : "Mike" } ] ← เปลี่ยนแล้ว
]
}
กฎการใช้ Dot Notation กับ Array Index
- Index เริ่มต้นที่ 0
- เขียนติดกัน:
array.0.field,array.1.2.subfield - ใช้ได้กับ
$set,$inc,$unset,$push(กับ $position), เป็นต้น - ข้อจำกัด: ไม่สามารถใช้ตัวแปร/Expression เป็น Index ได้ (ต้อง Hard-code)
วิธีทางเลือกสำหรับ Dynamic Index (MongoDB 3.6+)
// ใช้ $[] (All positional) + $filter หรือ $map ใน Pipeline
db.updateObjectDemo.updateOne(
{ id: 101 },
[{ $set: {
StudentDetails: {
$map: {
input: { $range: [0, { $size: "$StudentDetails" }] },
as: "i",
in: {
$cond: [
{ $eq: ["$$i", 1] }, // เงื่อนไข Index
{ $mergeObjects: [
{ $arrayElemAt: ["$StudentDetails", "$$i"] },
{ "1.StudentName": "Mike" } // แก้ Sub-index 1
]},
{ $arrayElemAt: ["$StudentDetails", "$$i"] }
]
}
}
}
}}]
);