仅更新 MongoDB 中的特定字段?
要仅更新特定字段,可以使用 $set 运算符。我们准备先创建一个带文档的集合
>db.updateOnlySpecificFieldDemo.insertOne({"EmployeeName":"John","EmployeeCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ea849d628fa4220163b72") } >db.updateOnlySpecificFieldDemo.insertOne({"EmployeeName":"Larry","EmployeeCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ea853d628fa4220163b73") } >db.updateOnlySpecificFieldDemo.insertOne({"EmployeeName":"David","EmployeeCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ea85bd628fa4220163b74") }
以下是用 find() 方法显示集合中所有文档的查询
> db.updateOnlySpecificFieldDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9ea849d628fa4220163b72"), "EmployeeName" : "John", "EmployeeCountryName" : "UK" } { "_id" : ObjectId("5c9ea853d628fa4220163b73"), "EmployeeName" : "Larry", "EmployeeCountryName" : "US" } { "_id" : ObjectId("5c9ea85bd628fa4220163b74"), "EmployeeName" : "David", "EmployeeCountryName" : "AUS" }
以下是用更新仅特定字段的查询
> db.updateOnlySpecificFieldDemo.update({_id:ObjectId("5c9ea849d628fa4220163b72")}, ... {$set: {"EmployeeName":"Robert"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
现在,你可以检查字段 “EmployeeName”:”John” 是否已更新为值 “Robert”。以下是查询
> db.updateOnlySpecificFieldDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9ea849d628fa4220163b72"), "EmployeeName" : "Robert", "EmployeeCountryName" : "UK" } { "_id" : ObjectId("5c9ea853d628fa4220163b73"), "EmployeeName" : "Larry", "EmployeeCountryName" : "US" } { "_id" : ObjectId("5c9ea85bd628fa4220163b74"), "EmployeeName" : "David", "EmployeeCountryName" : "AUS" }
查看以上示例输出,“EmployeeName” 已成功更新。
广告