Project first item in an array to new field (MongoDB aggregation)

Hongbo Miao picture Hongbo Miao · Aug 29, 2016 · Viewed 24.7k times · Source

I am using Mongoose aggregation (MongoDB version 3.2).

I have a field users which is an array. I want to $project first item in this array to a new field user.

I tried

  { $project: {
    user: '$users[0]',
    otherField: 1
  }},

  { $project: {
    user: '$users.0',
    otherField: 1
  }},

  { $project: {
    user: { $first: '$users'},
    otherField: 1
  }},

But neither works.

How can I do it correctly? Thanks

Answer

Alex Blex picture Alex Blex · Aug 29, 2016

You can use arrayElemAt:

{ $project: {
    user: { $arrayElemAt: [ "$users", 0 ] },
    otherField: 1
}},