您可以使用$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 }
以下是update()
在MongDB中的函数内部执行加法的查询-
> 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 }