Home > Net >  MongoDB - Update field in nested array
MongoDB - Update field in nested array

Time:08-16

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

  1. Use $elemMatch to find the existence of id: 2 in nested arrays.

  2. 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

  1. Use $elemMatch to find the existence of id: 2 in nested arrays.

  2. 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
    }
  ]
})

Demo Solution 2 @ MongoPlayground

  • Related