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

การเพิ่มเงินเดือนพนักงาน 10% ใน MongoDB ด้วย $mul

คูณค่าตัวเลขฟิลด์ด้วยตัวคูณด้วย $mul แบบ Atomic

ตัวดำเนินการ $mul ใช้คูณค่าของฟิลด์ตัวเลขด้วยตัวเลขที่ระบุ เหมาะสำหรับการเพิ่มร้อยละ เช่น เพิ่มเงินเดือน 10% (คูณ 1.1) ลดราคา 20% (คูณ 0.8) ฯลฯ

ตัวอย่างข้อมูลทดสอบ

> db.demo417.insertOne({ "EmployeeName": "Chris", "EmployeeSalary": 500 });
> db.demo417.insertOne({ "EmployeeName": "Mike", "EmployeeSalary": 1000 });

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

> db.demo417.find();

ผลลัพธ์:

{ "_id": ObjectId("..."), "EmployeeName": "Chris", "EmployeeSalary": 500 }
{ "_id": ObjectId("..."), "EmployeeName": "Mike", "EmployeeSalary": 1000 }

คำสั่งเพิ่มเงินเดือน 10% ให้ Chris และ Mike

> db.demo417.update(
  { "EmployeeName": { $in: ["Chris", "Mike"] } },
  { $mul: { EmployeeSalary: 1.1 } },
  { multi: true }
);

ผลลัพธ์: WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })

แสดงข้อมูลหลังอัปเดต

> db.demo417.find();

ผลลัพธ์:

{ "_id": ObjectId("..."), "EmployeeName": "Chris", "EmployeeSalary": 550 }
{ "_id": ObjectId("..."), "EmployeeName": "Mike", "EmployeeSalary": 1100 }

คำอธิบาย

  • { $in: ["Chris", "Mike"] }: เงื่อนไขค้นหา EmployeeName เป็น Chris หรือ Mike
  • $mul: { EmployeeSalary: 1.1 }: คูณ EmployeeSalary ด้วย 1.1 (เพิ่ม 10%)
  • { multi: true }: อัปเดตทุกเอกสารที่ match (รูปแบบเก่า)

รูปแบบใหม่ที่แนะนำ

> db.demo417.updateMany(
  { "EmployeeName": { $in: ["Chris", "Mike"] } },
  { $mul: { EmployeeSalary: 1.1 } }
);

ตัวดำเนินการคำนวณตัวเลขอื่นๆ

Operatorคำอธิบายตัวอย่าง
$incบวก/ลบค่าคงที่{ $inc: { salary: 500 } }
$mulคูณด้วยตัวเลข{ $mul: { salary: 1.1 } }
$minตั้งค่าเป็นค่าน้อยกว่าเดิม{ $min: { score: 50 } }
$maxตั้งค่าเป็นค่ามากกว่าเดิม{ $max: { score: 100 } }

ข้อดีของ $mul

  • Atomic - ไม่มี Race Condition
  • ไม่ต้องอ่านค่าเก้าก่อน คำนวณเองฝั่ง Server
  • รองรับทศนิยมได้