My requirement is to fetch the last updated document from embedded list of documents. Is there any query or aggregation I can write to get only the document that is last updated from this list of documents?
Document Structure
{
_id: "123",
updatedAt: 2023-03-02T14:04:37.925+00:00,
embedded : [
{
_id:"456",
updatedAt: 2023-04-02T14:04:37.925+00:00
},
{
_id:"789",
updatedAt: 2023-04-010T14:04:37.925+00:00
}
]
}
I want to fetch the document with _id: "789" as it is the last updated document in the embedded list. I want to do this for all the root documents which has embedded key.
Expected Result
{
_id: "123",
updatedAt: 2023-03-02T14:04:37.925+00:00,
embedded : [
{
_id:"789",
updatedAt: 2023-04-010T14:04:37.925+00:00
}
]
}
>Solution :
If your MongoDB version is 5.2 and above, you can work with $sortArray to sort the document in the array and next with $first to get the first element.
db.collection.aggregate([
{
$set: {
embedded: [
{
$first: {
$sortArray: {
input: "$embedded",
sortBy: {
updatedAt: -1
}
}
}
}
]
}
}
])