Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 276
Hongbo Miao Avatar asked Aug 28 '16 22:08

Hongbo Miao


People also ask

How do I get an element from an array in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do I project specific fields in MongoDB?

Project Specific Array Elements in the Returned Array For fields that contain arrays, MongoDB provides the following projection operators for manipulating arrays: $elemMatch , $slice , and $ . $elemMatch , $slice , and $ are the only way to project specific elements to include in the returned array.


1 Answers

Update:

Starting from v4.4 there is a dedicated operator $first:

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

It's a syntax sugar to the

Original answer:

You can use arrayElemAt:

{ $project: {     user: { $arrayElemAt: [ "$users", 0 ] },     otherField: 1 }}, 
like image 119
Alex Blex Avatar answered Sep 16 '22 13:09

Alex Blex