Hi there,
This is my first post here, I’m fairly new to mongoDB.
I have the following structure in a collection called agreements:
basicData.owners.relatedJson.basicData.devices.equipmentID
Where owners
and devices
are lists of objects.
This structure is quite complex, and it’s worth noting that there is no guarantee the relatedJson
object or the devices
list exist.
I would like to rename the field eqiupmentID
to equipmentId
.
I have tried modifying a similar query that renames a field in a nested object in a nested list to suit this purpose, so far I’ve got the following:
db.serviceAgreement.updateMany({"basicData.serviceRecipients.relatedJson.basicData.devices.equipmentID": {$exists: true}},
[
{
$set: {
"basicData.serviceRecipients": {
$map: {
input: "$basicData.serviceRecipients",
in: {
$mergeObjects: [
"$$this",
{
$cond: [
{
$ne: [
"$$this.relatedJson",
undefined
]
},
{
relatedJson : {
$mergeObjects: [
"$$this.relatedJson.basicData",
{
$cond: [
{
$ne: [
"$$this.relatedJson.basicData",
undefined
]
},
{
basicData : {
$mergeObjects: [
"$$this.relatedJson.basicData",
{
$cond: [
{
$ne: [
"$$this.relatedJson.basicData.devices,
undefined
]
},
{
"$$this.devices": {
$map: {
}
}
},
{}
]
}
]
}
},
{}
],
}
]
}
},
{}
]
}
]
}
}
}
}
},
{
$unset: "basicData.serviceRecipients.relatedJson.basicData.devices.equipmentID"
}
])
I’m now looking at "$$this.devices":
and calling $map
in there, and mapping each device with the new name. Is this the correct approach? will this work?
My original plan was to add the new field equipmentId
and remove the old one (see the $unset
call at the end) but I cannot get that to work when working with lists of lists.
Any advice either way would be greatly appreciated.
I would prefer to add the new field the remove the old one WITHOUT having to specify every other field in each device
object as some of those may contain more nested objects.