僅遞增 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 }
廣告