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

เพิ่มค่าเฉพาะฟิลด์เดียวในเอกสาร MongoDB


เพื่ออัปเดตเฉพาะค่าเดียวและเพิ่มค่าใน MongoDB ให้ใช้ $inc ร่วมกับ update() มาสร้างคอลเลกชันพร้อมเอกสารกันก่อน

> db.demo698.insertOne({Score:78}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6d8a4551299a9f98c9398") } > db.demo698.insertOne({Score:56}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6d8a7551299a9f98c9399") } > db.demo698.insertOne({Score:65}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6d8aa551299a9f98c939a") } > db.demo698.insertOne({Score:88}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6d8b0551299a9f98c939b") }

แสดงเอกสารทั้งหมดจากคอลเลกชันด้วยเมธอด find()

> db.demo698.find();

จะได้ผลลัพธ์ดังนี้

{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 } { "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 } { "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 } { "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 88 }

คำสั่งสำหรับเพิ่มค่าเฉพาะฟิลด์เดียว

> db.demo698.update({_id:ObjectId("5ea6d8b0551299a9f98c939b")},{$inc:{Score:12}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

แสดงเอกสารทั้งหมดจากคอลเลกชันด้วยเมธอด find()

> db.demo698.find();

จะได้ผลลัพธ์ดังนี้

{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 } { "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 } { "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 } { "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 100 }