How to find latest entries in array over all MongoDB documents?

To find latest entries in array over all MongoDB documents, use the aggregate() method with $unwind to flatten arrays, $sort to order by the desired field, and $limit to get the top entries.

Syntax

db.collection.aggregate([
    { "$unwind": "$arrayField" },
    { "$sort": { "arrayField.sortField": -1 } },
    { "$limit": numberOfEntries }
]);

Sample Data

db.demo179.insertMany([
    {
        "Name": "Chris",
        "Details": [
            {
                "Id": 101,
                "Subject": "MongoDB"
            },
            {
                "Id": 102,
                "Subject": "MySQL"
            }
        ]
    },
    {
        "Name": "David",
        "Details": [
            {
                "Id": 103,
                "Subject": "Java"
            },
            {
                "Id": 104,
                "Subject": "C"
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3980299e4f06af551997f9"),
        ObjectId("5e39802a9e4f06af551997fa")
    ]
}

Example: Find Latest 2 Entries by Id

The following query finds the latest 2 entries across all documents based on the highest Id values ?

db.demo179.aggregate([
    { "$unwind": "$Details" },
    { "$sort": { "Details.Id": -1 } },
    { "$limit": 2 },
    {
        "$group": {
            "_id": "$Details.Id",
            "Name": { "$first": "$Name" },
            "Details": { "$push": "$Details" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "Name": 1,
            "Details": 1
        }
    }
]);
{ "Name": "David", "Details": [ { "Id": 104, "Subject": "C" } ] }
{ "Name": "David", "Details": [ { "Id": 103, "Subject": "Java" } ] }

How It Works

  • $unwind − Flattens the Details array, creating separate documents for each array element
  • $sort − Orders documents by Details.Id in descending order (-1)
  • $limit − Restricts results to the top 2 entries
  • $group − Groups by Details.Id and reconstructs the array structure
  • $project − Formats the final output by excluding _id field

Conclusion

Use aggregation pipeline with $unwind, $sort, and $limit to find the latest entries across all array elements in MongoDB documents. This approach flattens arrays first, then applies sorting to identify the most recent entries.

Updated on: 2026-03-15T01:40:12+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements