如何在 MongoDB 中使用 update() 函式進行增量?
可以使用 $inc 運算子來進行增量。讓我們首先使用文件建立一個集合 −
> 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")
}使用 find() 方法顯示集合中所有文件的查詢如下 −
> 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
}使用 MongDB 中的 update() 函式執行加法的查詢如下 −
> db.addInUpdateFunctionDemo.update({_id : ObjectId("5cd2b407345990cee87fd895")},{$inc: {PlayerScore: 201}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })讓我們再次檢查所有文件 −
> db.addInUpdateFunctionDemo.find().pretty();
這將產生以下輸出 −
{
"_id" : ObjectId("5cd2b3f4345990cee87fd893"),
"PlayerName" : "Chris",
"PlayerScore" : 78
}
{
"_id" : ObjectId("5cd2b3fc345990cee87fd894"),
"PlayerName" : "Robert",
"PlayerScore" : 88
}
{
"_id" : ObjectId("5cd2b407345990cee87fd895"),
"PlayerName" : "David",
"PlayerScore" : 300
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP