如何使用 MongoDB Update() 方法设置整个字段的记录?
可以结合 $set 运算符和 update() 使用。我们先使用文档创建一个集合 -
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd506fe2cba06f46efe9efa")
}
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd507022cba06f46efe9efb")
}
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd507022cba06f46efe9efc")
}
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd507032cba06f46efe9efd")
}以下是使用 find() 方法显示集合中所有文档的查询 -
> db.workingOfUpdateMethod.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cd506fe2cba06f46efe9efa"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efb"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efc"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507032cba06f46efe9efd"), "ClientCountryName" : "AUS" }以下是更新和设置整个字段的查询。这里,我们正在更新字段“ClientCountryName” -
> db.workingOfUpdateMethod.update(
... {"ClientCountryName" : "AUS"},
... {$set: {"ClientCountryName" : "UK"}},
... {multi: true});
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })让我们再次检查所有文档 -
> db.workingOfUpdateMethod.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cd506fe2cba06f46efe9efa"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efb"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efc"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507032cba06f46efe9efd"), "ClientCountryName" : "UK" }
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP