update()
在MongoDB中使用以更新数组对象。还需要使用点符号。让我们创建一个包含文档的集合-
> db.demo489.insertOne( ... { ... ... ... details : [{ ... id : 101, ... "Info1" : { ... "StudentName" : "Chris" ... }, ... "Info2" : { ... "TeacherName" : "David" ... } ... }, ... { ... id : 102, ... "Info1" : { ... "StudentName" : "Carol" ... }, ... "Info2" : { ... "TeacherName" : "Mike" ... } ... } ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8356e0b0f3fa88e22790ba") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo489.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8356e0b0f3fa88e22790ba"), "details" : [ { "id" : 101, "Info1" : { "StudentName" : "Chris" }, "Info2" : { "TeacherName" : "David" } }, { "id" : 102, "Info1" : { "StudentName" : "Carol" }, "Info2" : { "TeacherName" : "Mike" } } ] }
以下是更新数组对象的查询-
> db.demo489.update({"details.id":102}, ... {$set: {"details.$.Info1.StudentName":"Robert", ... "details.$.Info2.TeacherName":"John", ... "details.$.CountryName" : "US" ... ... } ... }) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo489.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e8356e0b0f3fa88e22790ba"), "details" : [ { "id" : 101, "Info1" : { "StudentName" : "Chris" }, "Info2" : { "TeacherName" : "David" } }, { "id" : 102, "Info1" : { "StudentName" : "Robert" }, "Info2" : { "TeacherName" : "John" }, "CountryName" : "US" } ] }