Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 ] }
        ]
      }
    }
  }
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading