Srikar
Srikar

Reputation: 371

MongoDB - Fetch document with the latest Timestamp from the list of nested documents

My requirement is to fetch the last updated document from the 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: ISODate("2023-03-02T14:04:37.925+00:00"),
  embedded: [
    {
      _id: "456",
      updatedAt: ISODate("2023-04-02T14:04:37.925+00:00")
    },
    {
      _id: "789",
      updatedAt: ISODate("2023-04-10T14: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 have embedded key.

Expected Result

{
   _id: "123",
   updatedAt: ISODate("2023-03-02T14:04:37.925+00:00"),
   embedded: [
     {
       _id: "789",
       updatedAt: ISODate("2023-04-10T14:04:37.925+00:00")
     }
   ]
}

Upvotes: 0

Views: 42

Answers (1)

Yong Shun
Yong Shun

Reputation: 51450

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
              }
            }
          }
        }
      ]
    }
  }
])

Demo @ Mongo Playground

Upvotes: 1

Related Questions