Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB – Fetch Document with the latest Timestamp from the list of nested documents

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Demo @ Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading