How can I extract entire documents based on how they compare with their whole collection?

To extract entire documents based on how they compare with their whole collection in MongoDB, use the $$ROOT variable within an aggregation pipeline. This allows you to preserve complete documents while performing grouping and comparison operations.

Syntax

db.collection.aggregate([
    {
        $project: {
            "field1": "$field1",
            "field2": "$field2", 
            "document": "$$ROOT"
        }
    },
    { $sort: { "field": 1 } },
    {
        $group: {
            "_id": { "groupField": "$field" },
            "result": { "$first": "$document" }
        }
    }
]);

Sample Data

db.demo743.insertMany([
    { id: 1, "ShippingDate": "2020-01-21", value: 50 },
    { id: 2, "ShippingDate": "2020-05-10", value: 30 },
    { id: 3, "ShippingDate": "2020-05-10", value: 60 },
    { id: 1, "ShippingDate": "2020-05-11", value: 75 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

Example: Get Latest Document per ID

Extract the most recent document for each id based on ShippingDate ?

db.demo743.aggregate([
    {
        "$project": {
            "id": "$id",
            "ShippingDate": "$ShippingDate",
            "MyDoc": "$$ROOT"
        }
    },
    {
        "$sort": { "ShippingDate": -1 }
    },
    {
        "$group": {
            "_id": { "id": "$id" },
            "Result": { "$first": "$MyDoc" }
        }
    },
    {
        "$project": {
            "Result.ShippingDate": 1,
            "Result.id": 1,
            "Result.value": 1,
            "_id": 0
        }
    }
]);
{ "Result": { "id": 3, "ShippingDate": "2020-05-10", "value": 60 } }
{ "Result": { "id": 2, "ShippingDate": "2020-05-10", "value": 30 } }
{ "Result": { "id": 1, "ShippingDate": "2020-05-11", "value": 75 } }

How It Works

  • $$ROOT captures the entire original document in the $project stage
  • $sort orders documents by ShippingDate (descending for latest first)
  • $group groups by id and uses $first to get the top document per group
  • $project reshapes the output to show only required fields

Conclusion

Use $$ROOT in aggregation pipelines to preserve entire documents while performing collection-wide comparisons and grouping operations. This technique is essential for extracting complete records based on specific criteria across the whole collection.

Updated on: 2026-03-15T03:54:35+05:30

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements