Search code examples
arraysmongodbif-statementaggregationprojection

mongodb $cond with $arrayElemAt as false condition inside aggregation


I'm inside the $project step.

{
  'res' : {$cond: [
    {$or: [{'$lte' :['$list', null]},
    {$eq: ['$list', []]}]
    }, 
    '$root_field', 
    {'$arrayElemAt': 
    ['$list.obj.field', 
    0]]}}
}

I want to check if a root list is null or empty. If it is, I want to take another root field, otherwise I need to take the first element of the list's object's value. But this is not written well, as compass tells me: enter image description here

I cannot find anything online relative to my case. How to manage the $arrayElemAt inside the $cond? I suppose that's the problem here


Solution

  • You misplaced on closing brackte:

    db.collection.aggregate([
      {
        $set: {
          res: {
            $cond: [
              {
                $or: [
                  { $lte: [ "$list", null ] },
                  { $eq: [ "$list", [] ] }
                ]
              },
              "$root_field",
              { $arrayElemAt: [ "$list.obj.field", 0 ] }
            ]
          }
        }
      }
    ])