MongoDB 查询可用于更新集合中的特定文档
要更新,请将 $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 } ] }
广告