I have a document to Mongodb update array of objects like this:
``` code ```
{
"myArray": [
{
"Key1": "string",
"key2": {
"entry": "aaa"
}
},
{
"Key1": "string",
"key2": {
"entry": "bbb"
}
}
]
}
``` code ```
And I want to modify the key2 field in each object of myArray. The expected result should be :
``` code ```
{
"myArray": [
{
"Key1": "string",
"key2Modified":"aaa"
},
{
"Key1": "string",
"key2Modified":"bbb"
}
]
}
``` code ```
Any help please ?
CodePudding user response:
use $map
in $set
db.collection.update({},
[
{
$set: {
"myArray": {
$map: {
input: "$myArray",
as: "a",
in: {
Key1: "$$a.Key1",
key2Modified: "$$a.key2.entry"
}
}
}
}
}
])