Using $redact in MongoDB aggregate?

The $redact stage in MongoDB aggregation pipeline restricts document contents based on information stored within the documents themselves. It uses conditional logic to decide whether to keep, prune, or descend into document fields.

Syntax

db.collection.aggregate([
    {
        $redact: {
            $cond: {
                if: <expression>,
                then: "$$KEEP" | "$$PRUNE" | "$$DESCEND",
                else: "$$KEEP" | "$$PRUNE" | "$$DESCEND"
            }
        }
    }
]);

Sample Data

db.demo546.insertMany([
    {"Value1": 10, "Value2": 20},
    {"Value1": 40, "Value2": 30, "Value3": 50},
    {"Value1": 100, "Value2": 200, "Value3": null},
    {"Value1": 400, "Value2": 1000, "Value3": null},
    {"Value1": 400, "Value2": 200, "Value3": null},
    {"Value1": 400, "Value2": 1000, "Value3": 60}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8e263f9e5f92834d7f05d7"),
        ObjectId("5e8e26549e5f92834d7f05d8"),
        ObjectId("5e8e26619e5f92834d7f05d9"),
        ObjectId("5e8e26e09e5f92834d7f05da"),
        ObjectId("5e8e26f59e5f92834d7f05db"),
        ObjectId("5e8e27159e5f92834d7f05dc")
    ]
}

Example: Filter Documents with Multiple Conditions

Find documents where Value1 is less than Value2 AND Value3 exists (not null) ?

db.demo546.aggregate([
    {
        $redact: {
            $cond: {
                if: {
                    $and: [
                        { $lt: ["$Value1", "$Value2"] },
                        { $ifNull: ["$Value3", false] }
                    ]
                },
                then: "$$KEEP",
                else: "$$PRUNE"
            }
        }
    }
]);
{ "_id": ObjectId("5e8e27159e5f92834d7f05dc"), "Value1": 400, "Value2": 1000, "Value3": 60 }

How It Works

  • $$KEEP ? Include the entire document in results
  • $$PRUNE ? Exclude the document from results
  • $$DESCEND ? Recursively apply redact to subdocuments
  • $ifNull ? Returns false if Value3 is null/missing, otherwise true

Conclusion

The $redact stage provides powerful document-level filtering based on field values and conditions. It's particularly useful for implementing field-level security or complex conditional document filtering in aggregation pipelines.

Updated on: 2026-03-15T03:32:14+05:30

707 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements