Reputation: 1292
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
Upvotes: 1
Views: 69
Reputation: 22296
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"
}
}
])
For lesser Mongo versions you have to read the document first and then use the values for the update.
Upvotes: 1