I am having the below document structure
[
{
"network_type": "ex",
"rack": [
{
"xxxx": {
"asn": 111111,
"nodes": {
"business": [
"sk550abcc1eb01.abc.com",
"sk550abcc1eb10.abc.com",
"sk550abcc1eb19.abc.com",
"sk550abcc1eb28.abc.com"
]
},
"region": "ex-01",
"zone": "01a"
}
}
]
}
]
I need to rename/update the key array element "xxxx" to "details".
I tried the below command , but it doesn't seem to work.
db.collection.update({},
{
$rename: {
"rack.xxxx": "details"
}
})
LINK : https://mongoplayground.net/p/9dcDP-VKZ55
Please help me.
CodePudding user response:
You can't direct $rename the field name which is within the array.
Instead,
Iterate with document(s) in the
rankarray, create thedetailsfield with the value ofxxxxand next append this field to each document.Remove the path with
$rank.xxxxto remove thexxxxfield from the document(s) in therankarray.
db.collection.update({},
[
{
$set: {
rack: {
$map: {
input: "$rack",
in: {
$mergeObjects: [
{
"details": "$$this.xxxx"
},
"$$this"
]
}
}
}
}
},
{
$unset: "rack.xxxx"
}
])
