Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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? ReturnsfalseifValue3is null/missing, otherwisetrue
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.
Advertisements
