Home > Software engineering >  MongoDB update - set field from nested field
MongoDB update - set field from nested field

Time:01-18

I want to set a field to a value of a nested field

given

{
  "_id":"myId",
  "data":{
    "id":"asdfasdfasdf",
    "text":"Wonderful text"
  }
}

expected

{
  "_id":"myId",
  "messageId":"asdfasdfasdf",
  "data":{
    "id":"asdfasdfasdf",
    "text":"Wonderful text"
  }
}

Is there a possibility to do something like this?

db.myCollection.updateMany({},{ $set: {"messageId": "$data.id"} },false,true)

I am using MongoCompass -> _MongoSH

CodePudding user response:

Yes, it's possible doing this using pipelined updates, added at version 4.2.

This is how you use it:

db.collection.updateMany(
{},
[
  {
    $set: {
      "message": "$data.id"
    }
  }
])

Mongo Playground

For lesser Mongo versions you have to read the document first and then use the values for the update.

  •  Tags:  
  • Related