Project nested array field values by their indexes in aggregation

Viewed 3850

I'm doing an aggregation in MongoDB which should have an array fields projection in its $project stage . But I can't access array fields by their indexes :

{//projection stage
  $project: {
    'foo' : { '$ifNull' : ['$bar.0.baz.0.qux', '*'] }
  }
}

This sets foo to an empty array . bar is a multidimensional array field. my MongoDB version is 3.2 . What can I do for this without the hassle of $unwind/$group old heavy solution ?

Thanks for your help .

2 Answers

Use multiple $project stage with $arrayElemAt operator with temporary fields.

{$project:{"tmp": {$arrayElemAt:["$bar",0]}}}, {$project:{"tmp2": {$arrayElemAt:["$tmp.baz",0]}}}

than your value is at $tmp2.qux.

Related