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

อัปเดต Array ใน MongoDB ด้วย Index แบบ Variable (Dynamic Index)

บทความนี้สาธิตวิธีอัปเดตค่าใน Array ตาม Index ที่เก็บอยู่ใน Variable (Dynamic Index) โดยสร้าง Object Update แบบ Dynamic ใน JavaScript ก่อนส่งเข้า update()

ไวยากรณ์หลัก

var yourIndexVariableName = yourIndexValue;
var anyVariableName = { "$set": {} };
anyVariableName["$set"]["yourFieldName." + yourIndexVariableName] = "yourValue";
db.yourCollectionName.update({ "_id": yourObjectId }, anyVariableName);

สร้างข้อมูลตัวอย่าง

> db.updateByVariableDemo.insertOne({"StudentSubjects":["MySQL","Java","SQL Server","PL/SQL"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd553c37924bb85b3f4893a") }

แสดงข้อมูลก่อนอัปเดต

> db.updateByVariableDemo.find().pretty();
{
  "_id" : ObjectId("5cd553c37924bb85b3f4893a"),
  "StudentSubjects" : [ "MySQL", "Java", "SQL Server", "PL/SQL" ]
}

อัปเดต Index 1 (Java) ให้กลายเป็น MongoDB

> var indexValue = 1;
> var valueToUpdate = { "$set": {} };
> valueToUpdate["$set"]["StudentSubjects." + indexValue] = "MongoDB";
> db.updateByVariableDemo.update(
  { "_id": ObjectId("5cd553c37924bb85b3f4893a") },
  valueToUpdate
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ตรวจสอบผลลัพธ์

> db.updateByVariableDemo.find().pretty();
{
  "_id" : ObjectId("5cd553c37924bb85b3f4893a"),
  "StudentSubjects" : [ "MySQL", "MongoDB", "SQL Server", "PL/SQL" ]
}

คำอธิบายเทคนิค

  1. สร้าง Variable indexValue เก็บ Index ที่ต้องการ (1 = ตัวที่ 2)
  2. สร้าง Update Object ว่าง { "$set": {} }
  3. ใช้ Bracket Notation สร้าง Key แบบ Dynamic: "StudentSubjects." + indexValue → "StudentSubjects.1"
  4. Assign ค่าใหม่: valueToUpdate["$set"]["StudentSubjects.1"] = "MongoDB"
  5. ส่ง Object นี้เข้า update()

วิธีทันสมัยกว่า (MongoDB 3.6+): ใช้ arrayFilters

db.collection.updateOne(
  { _id: ObjectId("...") },
  { $set: { "StudentSubjects.$[elem]": "MongoDB" } },
  { arrayFilters: [{ "elem": { $exists: true } }] } // ต้องระบุ index ผ่าน variable ไม่ได้โดยตรง
);

หมายเหตุ: arrayFilters ไม่รองรับ Index แบบ Variable โดยตรง วิธี Dynamic Object ยังคงเป็นวิธีที่ยืดหยุ่นที่สุด

ฟังก์ชันช่วยสะดวก (Helper Function)

function updateArrayByIndex(collection, docId, arrayField, index, newValue) {
  var updateObj = { $set: {} };
  updateObj.$set[arrayField + "." + index] = newValue;
  return db[collection].updateOne({ _id: docId }, updateObj);
}

// ใช้งาน
updateArrayByIndex("updateByVariableDemo", ObjectId("..."), "StudentSubjects", 1, "MongoDB");