要更新单个列表项,请使用位置运算符($)。首先让我们创建一个包含文档的集合-
> db.updateASingleListDemo.insertOne({ _id:1, "EmployeeName":"Chris", "EmployeeDetails": [ {"EmployeeId":"EMP-101","EmployeeSalary": 18999 }] }); { "acknowledged" : true, "insertedId" : 1 }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.updateASingleListDemo.find().pretty();
这将产生以下输出-
{ "_id" : 1, "EmployeeName" : "Chris", "EmployeeDetails" : [ { "EmployeeId" : "EMP-101", "EmployeeSalary" : 18999 } ] }
以下是更新MongoDB文档的单个列表项的查询。在这里,我们正在更新工资-
> db.updateASingleListDemo.update({_id: 1, 'EmployeeDetails.EmployeeId': "EMP-101"}, {$inc: {'EmployeeDetails.$.EmployeeSalary': 1}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查文档-
> db.updateASingleListDemo.find().pretty();
这将产生以下输出-
{ "_id" : 1, "EmployeeName" : "Chris", "EmployeeDetails" : [ { "EmployeeId" : "EMP-101", "EmployeeSalary" : 19000 } ] }