I'm trying to make a mongodb query byId that sorts the items in the 'history' array by the "updateDate" field and also shows only the first 2 items in the array.
{
"_id" : ObjectId("63b5c0f016c75b6c2e36575f"),
"history" : [
{
"adress" : [ "KKK" ],
"updateDate" : ISODate("2023-01-04T15:09:52.121-03:00")
},
{
"adress" : [ "YYY" ],
"updateDate" : ISODate("2023-01-04T15:10:03.303-03:00")
},
{
"adress" : [ "ZZZ" ],
"updateDate" : ISODate("2023-01-04T15:12:08.160-03:00")
}
]
}
I tried to do it like this, but it didn't work
db.collection.find(
{_id: ObjectId("63b5c0f016c75b6c2e36575f")},
{"history":{$slice: -2}}
)
.sort({"history.updateDate": -1})