如何在 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