要更新子对象,请使用$set运算符。让我们首先用文档创建一个集合-
>db.updateChildObjectsDemo.insertOne({"StudentName":"Chris","StudentOtherDetails":{"StudentSubject":"MongoDB","StudentCountryName":"AUS"}}); { "acknowledged" : true, "insertedId" : ObjectId("5ce964e078f00858fb12e91f") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.updateChildObjectsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ce964e078f00858fb12e91f"), "StudentName" : "Chris", "StudentOtherDetails" : { "StudentSubject" : "MongoDB", "StudentCountryName" : "AUS" } }
以下是更新MongoDB中子对象的查询-
> db.updateChildObjectsDemo.update({"StudentName" : "Chris"},{$set:{"StudentOtherDetails.StudentCountryName":"UK"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查文档-
> db.updateChildObjectsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ce964e078f00858fb12e91f"), "StudentName" : "Chris", "StudentOtherDetails" : { "StudentSubject" : "MongoDB", "StudentCountryName" : "UK" } }