如何在嵌套数组中查找和修改一个值?
要查找和修改嵌套数组中的值,可以使用 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 为“Online Banking Application”的 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" } ] }
广告