Project first item in an array to new field (Mongo

2019-01-18 02:59发布

问题:

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

回答1:

You can use arrayElemAt:

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