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

MongodbMongooseAggregation Framework

Mongodb Problem Overview


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

Mongodb Solutions


Solution 1 - Mongodb

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
}},

Solution 2 - Mongodb

If it is an array of objects and you want to use just single object field, ie:

{
 "users": [
    {name: "John", surname: "Smith"},
    {name: "Elon", surname: "Gates"}
   ]
}

you can use:

{ $project: { user: { $first: "$users.name" } } 

Edit (exclude case - after comment from @haytham)

In order to exclude a single field from a nested document in array you have to do 2 projections:

 { $project: { user: { $first: "$users" } } 

Which return whole first object, and then exclude field you do not want, ie:

{ $project: { "user.name" : 0 } 

Solution 3 - Mongodb

Starting Mongo 4.4, the aggregation operator $first can be used to access the first element of an array:

// { "users": ["Jean", "Paul", "Jack"] }
// { "users": ["Claude"] }
db.collection.aggregate([
  { $project: { user: { $first: "$users" } } }
])
// { "user" : "Jean" }
// { "user" : "Claude" }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHongbo MiaoView Question on Stackoverflow
Solution 1 - MongodbAlex BlexView Answer on Stackoverflow
Solution 2 - MongodbMichał SzkudlarekView Answer on Stackoverflow
Solution 3 - MongodbXavier GuihotView Answer on Stackoverflow