语法如下-
db.yourCollectionName.update({ }, { $set: { "yourOuterFieldName.yourInnerFieldName": "yourValue" } });
为了理解语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.updateNestedValueDemo.insertOne({"CustomerName":"Chris", ... "CustomerDetails":{"CustomerAge":25,"CustomerCompanyName":"Google","CustomerCityName":"US"}}); { "acknowledged" : true, "insertedId" : ObjectId("5c8fccc4d3c9d04998abf015") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.updateNestedValueDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8fccc4d3c9d04998abf015"), "CustomerName" : "Chris", "CustomerDetails" : { "CustomerAge" : 25, "CustomerCompanyName" : "Google", "CustomerCityName" : "US" } }
这是使用$set更新嵌套值/嵌入式文档的查询-
> db.updateNestedValueDemo.update({ }, { $set: { "CustomerDetails.CustomerCompanyName": "Dell" } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们使用find()
方法检查集合中的文档-
> db.updateNestedValueDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8fccc4d3c9d04998abf015"), "CustomerName" : "Chris", "CustomerDetails" : { "CustomerAge" : 25, "CustomerCompanyName" : "Dell", "CustomerCityName" : "US" } }
查看上面的示例输出,嵌套字段“ CustomerCompanyName”已从“ Google”更改为“ Dell”。