Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use $addFields (aggregation) only when a certain condition is met

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.

  • when using $cond its a boolean so I have to add a field with either date value or false
  • When using if I have to provide else, then conditions

Any ideas on how to achieve this?

like image 874
Deano Avatar asked Dec 30 '25 12:12

Deano


1 Answers

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

like image 61
turivishal Avatar answered Jan 01 '26 08:01

turivishal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!