MongoDB ไม่มีฟีเจอร์ Limit ตรงๆ สำหรับ $inc แต่สามารถทำได้โดยใช้ Query Condition ในส่วน Filter ของ update() เพื่ออัปเดตเฉพาะเอกสารที่ค่าฟิลด์อยู่วัฒนภายใต้เกณฑ์ที่กำหนด
ไวยากรณ์
db.collection.update(
{fieldName: {$lt: thresholdValue}},
{$inc: {fieldName: incrementValue}},
false, // upsert
true // multi (update หลายเอกสาร)
)
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.limitIncrementDemo.insertOne({"StudentId":101,"StudentScore":95});
{ "acknowledged": true, "insertedId": ObjectId("5cd2ce9eb64f4b851c3a13c3") }
> db.limitIncrementDemo.insertOne({"StudentId":102,"StudentScore":55});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea0b64f4b851c3a13c4") }
> db.limitIncrementDemo.insertOne({"StudentId":103,"StudentScore":67});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea1b64f4b851c3a13c5") }
> db.limitIncrementDemo.insertOne({"StudentId":104,"StudentScore":56});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea3b64f4b851c3a13c6") }
> db.limitIncrementDemo.insertOne({"StudentId":105,"StudentScore":79});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea4b64f4b851c3a13c7") }
แสดงข้อมูลก่อนอัปเดต
> db.limitIncrementDemo.find().pretty();
ผลลัพธ์:
{"_id": ObjectId("5cd2ce9eb64f4b851c3a13c3"), "StudentId": 101, "StudentScore": 95}
{"_id": ObjectId("5cd2cea0b64f4b851c3a13c4"), "StudentId": 102, "StudentScore": 55}
{"_id": ObjectId("5cd2cea1b64f4b851c3a13c5"), "StudentId": 103, "StudentScore": 67}
{"_id": ObjectId("5cd2cea3b64f4b851c3a13c6"), "StudentId": 104, "StudentScore": 56}
{"_id": ObjectId("5cd2cea4b64f4b851c3a13c7"), "StudentId": 105, "StudentScore": 79}
คำสั่ง: เพิ่มคะแนน 10 คะแนน เฉพาะนักเรียนที่คะแนน < 75
> db.limitIncrementDemo.update(
{StudentScore: {$lt: 75}},
{$inc: {StudentScore: 10}},
false, // upsert: false
true // multi: true
);
WriteResult({ "nMatched": 3, "nUpserted": 0, "nModified": 3 })
ตรวจสอบผลลัพธ์
> db.limitIncrementDemo.find().pretty();
ผลลัพธ์ (นักเรียน 102, 103, 104 ได้เพิ่มคะแนน | 101 และ 105 คะแนน >= 75 ไม่ได้รับผลกระทบ):
{"_id": ObjectId("5cd2ce9eb64f4b851c3a13c3"), "StudentId": 101, "StudentScore": 95}
{"_id": ObjectId("5cd2cea0b64f4b851c3a13c4"), "StudentId": 102, "StudentScore": 65}
{"_id": ObjectId("5cd2cea1b64f4b851c3a13c5"), "StudentId": 103, "StudentScore": 77}
{"_id": ObjectId("5cd2cea3b64f4b851c3a13c6"), "StudentId": 104, "StudentScore": 66}
{"_id": ObjectId("5cd2cea4b64f4b851c3a13c7"), "StudentId": 105, "StudentScore": 79}
สรุปเทคนิค
- ใช้ Query Filter (
{$lt: 75}) ควบคุมว่า $inc ทำงานกับเอกสารไหน - พารามิเตอร์ที่ 3 (
upsert) = false, พารามิเตอร์ที่ 4 (multi) = true - รูปแบบใหม่ (MongoDB 3.2+): ใช้
updateMany()แทนdb.limitIncrementDemo.updateMany( {StudentScore: {$lt: 75}}, {$inc: {StudentScore: 10}} ); - เทคนิคนี้ใช้ได้กับ
$set,$mul,$min,$maxและ Operator อื่นๆ เช่นกัน