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

วิธี Conditional Upsert/Update ใน MongoDB ด้วย $max Operator

ใช้ Operator $max เพื่ออัปเดตค่าเฉพาะเมื่อค่าใหม่ มากกว่า ค่าเดิม (Conditional Update) เหมาะสำหรับเก็บค่าสูงสุด (High Score, Max Value)

รูปแบบคำสั่ง

db.collection.update(
    { query },
    { $max: { "fieldName": newValue } }
);

อัปเดต ก็ต่อเมื่อ newValue > ค่าปัจจุบัน

ตัวอย่างเต็มรูปแบบ

1. สร้างข้อมูลตัวอย่าง (มี BiggestScore)

> db.conditionalUpdatesDemo.insertOne({ "_id": 100, "StudentFirstScore": 89, "StudentSecondScore": 78, "BiggestScore": 89 });
> db.conditionalUpdatesDemo.insertOne({ "_id": 101, "StudentFirstScore": 305, "StudentSecondScore": 560, "BiggestScore": 1050 });
> db.conditionalUpdatesDemo.insertOne({ "_id": 103, "StudentFirstScore": 560, "StudentSecondScore": 789, "BiggestScore": 880 });

2. แสดงข้อมูลก่อน

{ "_id" : 100, "StudentFirstScore" : 89, "StudentSecondScore" : 78, "BiggestScore" : 89 }
{ "_id" : 101, "StudentFirstScore" : 305, "StudentSecondScore" : 560, "BiggestScore" : 1050 }
{ "_id" : 103, "StudentFirstScore" : 560, "StudentSecondScore" : 789, "BiggestScore" : 880 }

3. ลองอัปเดต BiggestScore = 150 สำหรับ _id: 100 (ค่าเดิม 89)

> db.conditionalUpdatesDemo.update(
    { _id: 100 },
    { $max: { "BiggestScore": 150 } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

150 > 89 → อัปเดตสำเร็จ

4. ลองอัปเดต BiggestScore = 50 สำหรับ _id: 100 (ค่าปัจจุบัน 150)

> db.conditionalUpdatesDemo.update(
    { _id: 100 },
    { $max: { "BiggestScore": 50 } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

50 < 150 → ไม่อัปเดต (nModified: 0)

5. ผลลัพธ์สุดท้าย

{ "_id" : 100, "BiggestScore" : 150 }  // อัปเดตจาก 89 → 150, ไม่อัปเดต 50
{ "_id" : 101, "BiggestScore" : 1050 }
{ "_id" : 103, "BiggestScore" : 880 }

Operator คู่: $min

db.collection.update(
    { query },
    { $min: { "fieldName": newValue } }
);

อัปเดตก็ต่อเมื่อ newValue < ค่าปัจจุบัน (เก็บค่าต่ำสุด)

Comparison Operators สำหรับ Conditional Update

Operatorเงื่อนไขอัปเดตUse Case
$maxnew > currentHigh Score, Max Temperature
$minnew < currentLow Score, Min Price
$incAlwaysCounter, Accumulator
$setAlwaysGeneral Update

สรุป

  • $max = Conditional Update: อัปเดตก็ต่อเมื่อค่าใหม่มากกว่า
  • $min = Conditional Update: อัปเดตก็ต่อเมื่อค่าใหม่ควรน้อยกว่า
  • Atomic - ไม่ต้อง Check-Then-Update เอง (Race Condition Safe)
  • เหมาะสำหรับ Leaderboard, High Score, Min/Max Tracking