2

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}

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.