This is my collection structure in MongoDB:
{ _id: id, name: name, loans: [ [{id: 1, acName: "ABC"}], [{id: 2, acName: "DEF"}], [{id: 3, acName: "GHI"}] ]}How can I updateacName of a specific ID? Let's say, I want to updateacName ofid 2. How can I do that?
1 Answer1
Solution 1: Without arrayFilters
Use
$elemMatchto find the existence ofid: 2in nested arrays.With all positional operator (
$[]) to update the respective document field.
db.collection.update({ "loans": { $elemMatch: { $elemMatch: { id: 2 } } }},{ $set: { "loans.$.$[].acName": "<NEW VALUE>" }})Demo Solution 1 @ MongoPlayground
Solution 2: With arrayFilters
Use
$elemMatchto find the existence of id: 2 in nested arrays.With filtered positional operator (
$[<identifier>]) and arrayFilters to update the respective document field.
db.collection.update({ "loans": { $elemMatch: { $elemMatch: { id: 2 } } }},{ $set: { "loans.$.$[loan].acName": "<NEW VALUE>" }},{ arrayFilters: [ { "loan.id": 2 } ]})4 Comments
Explore related questions
See similar questions with these tags.