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
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.
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.
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 }},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With