Projecting a field's value inside an array that is in an object

Hello everyone, I need some help regarding projection of a particular field inside a deeply nested document.

Consider the following document structure -

"_id": 2020,
    "students": {
        "1": [{
            "_id": {
                "$oid": "5f093dc05706776c704f1ce6"
            },
            "admitted": {
                "$date": "2020-07-11T12:42:06.581Z"
            },
            "type": "management quota",
            "paid": 4,
            "fOccupation": "Businessman"
        },{
            "_id": {
                "$oid": "5f093dc05706776c704f1ce8"
            },
            "admitted": {
                "$date": "2020-07-11T12:46:06.581Z"
            },
            "type": "handicapped",
            "paid": 0,
            "fOccupation": "Beggar"
        }],
        "2": [{}]
    }

Now, I need the data in the following manner:

fOccupation:["Businessman","Beggar"] //An array of all values under object with key = "1"
paid: 0 // Last value of 'paid' in the array under object with key = "1"

I am able to return the fOccupation array just fine but I am not able to project the last value (array.length - 1) of the “paid” property. Please help me out in this regard.

var pipeline = [{
  $match:{
    _id:2020
  }
},{
  $project:{
    _id:0,
    fOccupation: "$students.1.fOccupation",
    paid: {$arrayElemAt: ["$students.1.paid",-1]}
  }
}];

db.collection.aggregate(pipeline) gives the required result. The number in ‘student.1.X’ represents the class number which can be changed accordingly in the program.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.