I'm trying to add field only when a certain condition is met, for example, if an array size > 0 then use $addFields to add field "date", otherwise don't add it.
$cond its a boolean so I have to add a field with either date value or falseif I have to provide else, then conditionsAny ideas on how to achieve this?
Starting in MongoDB 3.6, you can use the variable $$REMOVE in aggregation expressions to conditionally suppress a field. For an example, see Conditionally Exclude Fields,
{
$addFields: {
date: {
$cond: [
{ $gt: [{ $size: "$array" }, 0] },
"date field", // your date field
"$$REMOVE"
]
}
}
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With