Home > OS >  How to update a subfield element from another subfield element in mongodb?
How to update a subfield element from another subfield element in mongodb?

Time:03-25

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

CodePudding user response:

You can use $ operator like this:

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

CodePudding user response:

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

  • Related