How can I update a field when a condition is met?
if option.returned
is true
I want to update the field status:'returned'
.
orders: [
{ id: 100, status: "shipped", options: [{ returned: true }] },
{ id: 101, status: "packed", options: [{ quick: true }] },
{ id: 102, status: "ordered" }
]
desired result: [
{ id: 100, status: "returned", options: [{ returned: true }] },
// ^- updated status because returned: true
{ id: 101, status: "packed", options: [{ quick: true }] },
{ id: 102, status: "ordered" }
]
I can set an additional field returned
, extracting the value from the array into the field.
{
$set: {
returned: "$options.returned"
}
},
{
$unwind: {
path: "$returned",
preserveNullAndEmptyArrays: true
}
}
orders: [
{ id: 100, status: "shipped", options: [{ returned: true }], returned: true }, // extracted value from array
{ id: 101, status: "packed", options: [{ quick: true }] },
{ id: 102, status: "ordered" }
]
But so far all attempts combining $set
and $cond
to overwrite status
have failed for me.
How can I update status
when returned
is set, otherwise keep the previous value?
Thanks,
bluepuma