LeoGarcia
LeoGarcia

Reputation: 81

MongoDB aggregation get last element's field from nested array

I want to aggregate and display only the last object in a nested array This is my DB:

[{
  "firstName": "Shaun",
  "salary": [
    {
    "id":1,
    "rate": 250,
    },
    {
    "id":2,
     "rate": 290,
    }
  ]
},{
  "firstName": "Julian",
  "salary": [
    {
    "id":1,
     "rate": 750,      
    },
    {
    "id":2,
     "rate": 760,      
    },
    {
    "id":3,
     "rate": 790,      
    },
  ]
}
}]

My desired result is :

{"firstName": "Shaun", "rate":290},{"firstName": "Julian", "rate":790}

Upvotes: 2

Views: 1462

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Try below aggregation query which uses $arrayElemAt to get last element from array salary.rate :

db.collection.aggregate({
  $project: {
    firstName: 1,
    rate: { $arrayElemAt: [ "$salary.rate", -1 ] }
  }
})

Test : mongoplayground

Upvotes: 4

Related Questions