更新MongoDB中的数组元素?
使用$addToSet运算符更新数组元素。首先让我们创建一个包含文档的集合-
> db.updateArrayDemo.insertOne( ... { ... ... "ClientDetails" : [ ... { ... "ClientName" : "John", ... "DeveloperDetails" : [ ] ... }, ... { ... "ClientName" : "Larry", ... "DeveloperDetails" : [ ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ccf465edceb9a92e6aa1960") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.updateArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ccf465edceb9a92e6aa1960"), "ClientDetails" : [ { "ClientName" : "John", "DeveloperDetails" : [ ] }, { "ClientName" : "Larry", "DeveloperDetails" : [ ] } ] }
以下是更新数组元素的查询-
> db.updateArrayDemo.update({ "ClientDetails.ClientName": "Larry" }, { $addToSet: { "ClientDetails.$.Technology": { 'DeveloperName': "Chris", 'WorkExperience':5 } } }, false, true); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们检查数组元素是否已更新-
> db.updateArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ccf465edceb9a92e6aa1960"), "ClientDetails" : [ { "ClientName" : "John", "DeveloperDetails" : [ ] }, { "ClientName" : "Larry", "DeveloperDetails" : [ ], "Technology" : [ { "DeveloperName" : "Chris", "WorkExperience" : 5 } ] } ] }