How to use $exists operator inside $reduce stage?

Hi there,

I try to use a $exists operator inside $reduce stage, but I get an error “Invalid $set :: caused by :: Unrecognized expression ‘$exists’”

{
$set:
{
  childrenWithoutEndDate: {
    $reduce: {
      input:'$children',
      initialValue:[],
      in:{ 
        $let:{
          vars:{
            hasEndDate: {$exists:['$$this.endDate',true]}
          },
          in:{
            $concatArrays:['$$value',{$cond:['$$hasEndDate',['$$this'],[]]}]
          }
        }
      }
    }
  }
}
}

Here is a short example of a document from my collection

children

thanks

Look at filter:

**
 * newField: The new field name.
 * expression: The new field expression.
 */
{
  lines: {$filter: {
    input: "$lines",
    cond: {$ne: ["$$this", ""]}
  }}
}

First filter out the undesirable elements, then on the next stage of the aggregation use $reduce
While it is one more step it is easier to follow. You can have a conditional in $reduce, but you need to have one output for each element in the array. In my example, create a string by concatenation using $reduce.
$reduce

Hi @Ilan_Toren,

The $filter aggregation is a good solution.

I need to keep only the subset that contain a “endDate” field.
When trying $exists operator I get an error

Do you know how to use $exists in $filter aggreagation ?

For example in the document below, only keep the first element

{
  "_id": "fr_TYPOLOGIE_SPE",
  "children": [
    {
      "startDate":  ISODate("2014-02-10T10:50:42.389Z") ,
      "endDate":  ISODate("2014-03-08T08:51:42.389Z") 
    },
    {
      "startDate": ISODate("2014-02-10T10:50:42.389Z")
  ]
}