如何在MongoDB中更新子文档数组?
要更新,请update()
与$set一起使用。让我们创建一个包含文档的集合-
>db.demo134.insertOne({"EmployeeId":101,"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeAge":27},{"EmployeeName":"Bob","EmployeeAge":28}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e319b2f68e7f832db1a7f7c") } >db.demo134.insertOne({"EmployeeId":102,"EmployeeDetails":[{"EmployeeName":"David","EmployeeAge":24},{"EmployeeName":"Carol","EmployeeAge":29}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e319b4468e7f832db1a7f7d") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo134.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e319b2f68e7f832db1a7f7c"), "EmployeeId" : 101, "EmployeeDetails" : [ { "EmployeeName" : "Chris", "EmployeeAge" : 27 }, { "EmployeeName" : "Bob", "EmployeeAge" : 28 } ] } { "_id" : ObjectId("5e319b4468e7f832db1a7f7d"), "EmployeeId" : 102, "EmployeeDetails" : [ { "EmployeeName" : "David", "EmployeeAge" : 24 }, { "EmployeeName" : "Carol", "EmployeeAge" : 29 } ] }
以下是更新MongoDB中子文档数组的查询-
> db.demo134.update( ... { ... "EmployeeId":101, ... "EmployeeDetails.EmployeeName":"Chris" ... }, ... { ... $set: { ... "EmployeeDetails.$.EmployeeName" : "Robert" ... } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo134.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e319b2f68e7f832db1a7f7c"), "EmployeeId" : 101, "EmployeeDetails" : [ { "EmployeeName" : "Robert", "EmployeeAge" : 27 }, { "EmployeeName" : "Bob", "EmployeeAge" : 28 } ] } { "_id" : ObjectId("5e319b4468e7f832db1a7f7d"), "EmployeeId" : 102, "EmployeeDetails" : [ { "EmployeeName" : "David", "EmployeeAge" : 24 }, { "EmployeeName" : "Carol", "EmployeeAge" : 29 } ] }