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

วิธีใช้ $inc ภายในฟังก์ชัน update() ของ MongoDB

ตัวดำเนินการ $inc ใช้สำหรับเพิ่มค่าฟิลด์ตัวเลขภายในคำสั่ง update() บทความนี้สาธิตการใช้งานพื้นฐานกับตัวอย่างผู้เล่นและคะแนน

สร้างคอลเลกชันและเพิ่มข้อมูลตัวอย่าง

> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"Chris","PlayerScore":78});
{ "acknowledged": true, "insertedId": ObjectId("5cd2b3f4345990cee87fd893") }
> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"Robert","PlayerScore":88});
{ "acknowledged": true, "insertedId": ObjectId("5cd2b3fc345990cee87fd894") }
> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"David","PlayerScore":99});
{ "acknowledged": true, "insertedId": ObjectId("5cd2b407345990cee87fd895") }

แสดงข้อมูลทั้งหมด

> db.addInUpdateFunctionDemo.find().pretty();

ผลลัพธ์:

{
  "_id": ObjectId("5cd2b3f4345990cee87fd893"),
  "PlayerName": "Chris",
  "PlayerScore": 78
}
{
  "_id": ObjectId("5cd2b3fc345990cee87fd894"),
  "PlayerName": "Robert",
  "PlayerScore": 88
}
{
  "_id": ObjectId("5cd2b407345990cee87fd895"),
  "PlayerName": "David",
  "PlayerScore": 99
}

คำสั่งเพิ่มค่าคะแนนด้วย $inc

เพิ่มคะแนนให้ David (PlayerScore) 201 คะแนน:

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

ตรวจสอบผลลัพธ์

> db.addInUpdateFunctionDemo.find().pretty();

คะแนนของ David เพิ่มจาก 99 เป็น 300:

{
  "_id": ObjectId("5cd2b3f4345990cee87fd893"),
  "PlayerName": "Chris",
  "PlayerScore": 78
}
{
  "_id": ObjectId("5cd2b3fc345990cee87fd894"),
  "PlayerName": "Robert",
  "PlayerScore": 88
}
{
  "_id": ObjectId("5cd2b407345990cee87fd895"),
  "PlayerName": "David",
  "PlayerScore": 300
}

จุดสำคัญ

  • $inc ทำงานได้กับฟิลด์ตัวเลขเท่านั้น
  • หากฟิลด์ไม่มีอยู่ จะสร้างฟิลด์ใหม่พร้อมตั้งค่าเท่ากับจำนวนที่เพิ่ม
  • รองรับค่าลบสำหรับการลดค่า (decrement)