How to update a subfield element from another subfield element in mongodb?

Viewed 52

Image this data structure :

{
_id: 1
 ...
sections: [
 { 
    Title: 'hello world',
    Title2: '',
 },
 {
    Title: 'goodbye',
    Title2: ''
 }
]
}

I need to update all Title2 from Title.

I tried things like :

db...update(
{  },
[{ $set: 
    { 
        "sections.Title2": "sections.Title",
     }
   }])

but without success. Also tried with updateMany and some variants like sections.$.Title2.

Thank you for any help

1 Answers

You can do via update + aggregation pipleine(mongod 4.2+) & $map as follow:

db.collection.update({
  sections: {
    $exists: true
  }
},
[
 {
  $addFields: {
    "sections": {
      $map: {
        input: "$sections",
        as: "s",
        in: {
          "Title": "$$s.Title",
          "Title2": "$$s.Title"
       }
      }
     }
    }
   }
 ],
 {
   multi: true
 })

Explained: Find and replace the existing sections with mapped the necessary array values for Title2 to Title. Add the option {multi:true} to update all documents in collection

playground

Improved version2:

db.collection.update({
  sections: {
   $exists: true
  }
},
[
 {
   $addFields: {
  "sections": {
    $map: {
      input: "$sections",
      as: "s",
      in: {
        $mergeObjects: [
          "$$s",
          {
            "Title2": "$$s.Title"
          }
        ]
      }
     }
    }
   }
  }
 ],
 {
  multi: true
 })

Explained: In this version you merge the changed value with the subdocument so you dont need to add every of the other fields that are nto going to be changed.

playground2

Related