บทความนี้จะสาธิตวิธีการเพิ่มค่าฟิลด์ (increment) ภายในเอกสาร MongoDB ที่มีโครงสร้างข้อมูลฝัง (nested/embedded document) โดยใช้ตัวดำเนินการ $inc
ตัวอย่างโครงสร้างข้อมูล
สมมติเรามีคอลเลกชันที่เก็บข้อมูลนักเรียนและคะแนนสอบซึ่งเป็นข้อมูลฝังอยู่ภายใน StudentDetails:
{
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 78
}
}
}
ขั้นตอนการสร้างคอลเลกชันและเพิ่มข้อมูล
> db.embeddedValueIncrementDemo.insertOne({
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 78
}
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd2b670345990cee87fd896")
}
แสดงข้อมูลทั้งหมดในคอลเลกชัน
> db.embeddedValueIncrementDemo.find().pretty();
ผลลัพธ์:
{
"_id": ObjectId("5cd2b670345990cee87fd896"),
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 78
}
}
}
คำสั่งเพิ่มค่าฟิลด์ที่ฝังอยู่ (Increment Embedded Field)
ใช้ $inc ร่วมกับ Dot Notation เพื่อระบุเส้นทางไปยังฟิลด์เป้าหมาย:
> db.embeddedValueIncrementDemo.update(
{ _id: new ObjectId("5cd2b670345990cee87fd896") },
{ $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } },
{ upsert: true, safe: true },
null
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
ตรวจสอบผลลัพธ์หลังอัปเดต
> db.embeddedValueIncrementDemo.find().pretty();
คะแนน MongoDB เพิ่มจาก 78 เป็น 98:
{
"_id": ObjectId("5cd2b670345990cee87fd896"),
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 98
}
}
}
สรุป
- ใช้
$incเพื่อเพิ่มค่าตัวเลข - ระบุเส้นทางฟิลด์ด้วย Dot Notation (เช่น
"StudentDetails.StudentScores.StudentMongoDBScore") - รองรับทั้ง embedded document และ nested array