要进行更新,请使用$set和UPDATE。让我们创建一个包含文档的集合-
>db.demo135.insertOne({"Details":[{"EmployeeId":101,"EmployeeName":"Chris","EmployeeSalary":45000},{"EmployeeId":102,"EmployeeName":"Chris","EmployeeSalary":45000}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e31a5ddfdf09dd6d085399c") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo135.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e31a5ddfdf09dd6d085399c"), "Details" : [ { "EmployeeId" : 101, "EmployeeName" : "Chris", "EmployeeSalary" : 45000 }, { "EmployeeId" : 102, "EmployeeName" : "Chris", "EmployeeSalary" : 45000 } ] }
以下是更新第二个文档的查询-
> db.demo135.update( ... { ... ... "Details.EmployeeId":102, ... ... }, ... { ... $set: { ... "Details.$.EmployeeName" : "John Doe" ... } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo135.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e31a5ddfdf09dd6d085399c"), "Details" : [ { "EmployeeId" : 101, "EmployeeName" : "Chris", "EmployeeSalary" : 45000 }, { "EmployeeId" : 102, "EmployeeName" : "John Doe", "EmployeeSalary" : 45000 } ] }