仅更新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”已成功更新。