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

เพิ่มค่าฟิลด์ใน MongoDB (Increment)

ใช้ $inc เพิ่ม/ลดค่าตัวเลขในฟิลด์

โอเปอเรเตอร์ $inc ใช้สำหรับเพิ่มค่า (Increment) หรือลดค่า (Decrement) ฟิลด์ตัวเลข โดยอัตโนมัติสร้างฟิลด์ใหม่ถ้ายังไม่มี

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

> db.incrementDemo.insertOne({"PlayerScore":100});
> db.incrementDemo.insertOne({"PlayerScore":290});
> db.incrementDemo.insertOne({"PlayerScore":560});

คำสั่งเพิ่มคะแนน 10 ให้เอกสารที่ _id ตรงกัน

> db.incrementDemo.update(
    { _id: ObjectId("5cc81ce28f9e6ff3eb0ce44f") },
    { $inc: { "PlayerScore": 10 } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ผลลัพธ์: 290 → 300

> db.incrementDemo.find().pretty();
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 }
{ "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 300 }
{ "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }

คุณสมบัติสำคัญของ $inc

  • Atomic: อ่าน-แก้ไข-เขียน ใน Operation เดียว ไม่มี Race Condition
  • รองรับค่าลบ: { $inc: { score: -5 } } (Decrement)
  • สร้างฟิลด์ใหม่ถ้ายังไม่มี: เริ่มจาก 0 แล้วบวก
  • ทำงานได้กับ Integer, Long, Double, Decimal

รูปแบบสมัยใหม่

// หนึ่งเอกสาร
db.incrementDemo.updateOne(
    { _id: ObjectId("...") },
    { $inc: { "PlayerScore": 10 } }
);

// หลายเอกสาร
db.incrementDemo.updateMany(
    { PlayerScore: { $lt: 500 } },
    { $inc: { "PlayerScore": 50 } }
);

Use Cases

  • นับ Views, Likes, Downloads
  • Inventory Management (Stock +/-)
  • Rate Limiting Counters
  • Leaderboard Scores