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 update acName
of a specific ID? Let's say, I want to update acName
of id
2. How can I do that?
CodePudding user response:
Solution 1: Without arrayFilters
Use
$elemMatch
to find the existence ofid: 2
in 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
$elemMatch
to 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
}
]
})