Hi all,
I have the following query, which has multiple $cond
and $ne
functions:
db.collection.updateMany({
"basicData.owners.relatedJson.basicData.devices.equipmentID": {
$exists: true
}
},
[
{
$set: {
"basicData.owners": {
$map: {
input: "$basicData.owners",
in: {
$mergeObjects: [
"$$this",
{
$cond: [
{
$ne: [
"$$this.relatedJson",
undefined
]
},
{
"relatedJson": {
$mergeObjects: [
"$$this.relatedJson",
{
$cond: [
{
$ne: [
"$$this.relatedJson.basicData",
undefined
]
},
{
"basicData": {
$mergeObjects: [
"$$this.relatedJson.basicData",
{
$cond: [
{
$ne: [
"$$this.relatedJson.basicData.devices",
undefined
]
},
{
"devices": {
$map: {
input: "$$this.relatedJson.basicData.devices",
in: {
$mergeObjects: [
"$$this",
{
equipmentId: "$$this.equipmentID",
}
]
}
}
}
},
{},
]
}
]
}
},
{},
]
}
]
}
},
{},
]
}
]
}
}
}
}
},
{
$unset: "basicData.owners.relatedJson.basicData.devices.equipmentID"
}
])
This query works mostly as expected. However, I noticed that if an object exists but has a value of null
, say relatedJson
in the above example then this update will create an empty relatedJson
value instead of leaving it null
.
This situation can arise if for example there is one owner in the owners list that satisfies the query filter, but there are others that don’t.
How can I modify the $cond
functions to exclude undefined
and null
objects?
I was thinking I could use the $in
function somehow, but I can’t get it to work.
Anyone got any ideas?
Many thanks,
Paul.