要查找和修改嵌套数组中的值,可以使用update命令。首先让我们创建一个包含文档的集合
> db.findAndModifyAValueInNestedArrayDemo.insertOne( { "CompanyName" : "Amazon", "DeveloperDetails" : [ { "ProjectName" : "Online Book Store", "TeamSize" : "5" }, { "ProjectName" : "Library Management System", "TeamSize" : "7" }, { "ProjectName" : "Online Banking Application", "TeamSize" : "15" } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5ca275226304881c5ce84b9f") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.findAndModifyAValueInNestedArrayDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca275226304881c5ce84b9f"), "CompanyName" : "Amazon", "DeveloperDetails" : [ { "ProjectName" : "Online Book Store", "TeamSize" : "5" }, { "ProjectName" : "Library Management System", "TeamSize" : "7" }, { "ProjectName" : "Online Banking Application", "TeamSize" : "15" } ] }
以下是在嵌套数组中查找和修改值的查询。我们正在将ProjectName的TeamSize修改为20:“在线银行应用程序”
> db.findAndModifyAValueInNestedArrayDemo.update( { DeveloperDetails: { $elemMatch: { ProjectName: "Online Banking Application" } } }, { $set: { 'DeveloperDetails.$.TeamSize': '20' } } ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们检查文档是否被修改为20
> db.findAndModifyAValueInNestedArrayDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca275226304881c5ce84b9f"), "CompanyName" : "Amazon", "DeveloperDetails" : [ { "ProjectName" : "Online Book Store", "TeamSize" : "5" }, { "ProjectName" : "Library Management System", "TeamSize" : "7" }, { "ProjectName" : "Online Banking Application", "TeamSize" : "20" } ] }