Home > Enterprise >  Mongodb update a specific nested document in an array field
Mongodb update a specific nested document in an array field

Time:05-01

how can I update discharged field where id is like 111 ?

{
   address:'123',
   txs:[
      {id:'111',discharged:false},
      {id:'222',discharged:false}
       ]
}

CodePudding user response:

Solution 1

db.collection.update({
  address: "123",
  "txs.id": "111"
},
{
  $set: {
    "txs.$.discharged": true
  }
})

Sample Mongo Playground for Solution 1

Or

Solution 2: With arrayFilters and filtered positional operator

db.collection.update({
  address: "123",
  
},
{
  $set: {
    "txs.$[tx].discharged": true
  }
},
{
  arrayFilters: [
    {
      "tx.id": "111"
    }
  ]
})

Sample Mongo Playground for Solution 2

  • Related