您可以将$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" }