$REDACT EXCLUDES ALL FIELDS AT THIS CURRENT DOCUMENT/EMBEDDED DOCUMENT LEVEL, WITHOUT FURTHER INSPECTION OF ANY OF THE EXCLUDED FIELDS.
RESOURCE: $redact (aggregation) — MongoDB Manual
The $redact stage in MongoDB aggregation allows you to restrict entire documents or content within documents from being outputted based on information stored in the documents themselves. It’s a powerful tool for controlling the visibility of data based on specific conditions.
Scenario
Suppose we have a collection of users, and we want to retrieve specific information about users named “sohrab.” We’ll demonstrate how to use $redact to achieve this.
User Data
Let’s consider the following sample user data:
const Users = [
{
"id": 1,
"name": "john",
"age": 30,
"phone": "+12324252525"
},
{
"id": 2,
"name": "tom",
"age": 25,
"phone": "+12323525225"
},
{
"id": 3,
"name": "sohrab",
"age": 23,
"phone": "+12232325225"
},
{
"id": 4,
"name": "sohrab",
"age": 25,
"phone": "+12232325225"
}
];
Step 1: Using $match
We start by using the $match stage to filter users with the name “sohrab”:
Users.aggregate([
{
$match: {
name: "sohrab"
}
}
]);
The results will include the following documents:
User with id = 3:
Age: 23
Name: “sohrab”
Phone: “+12232325225”
User with id = 4:
Age: 25
Name: “sohrab”
Phone: “+12232325225”
Step 2: Using $redact and $cond
Now let’s further limit the output. We want to keep only users with an age of 25. We’ll use $redact and $cond for this purpose:
Users.aggregate([
{
$match: {
name: "sohrab"
}
},
{
$redact: {
$cond: {
if: {
$eq: ["$age", 25]
},
then: "$$DESCEND", // Keep fields at this level
else: "$$PRUNE" // Exclude fields at this level
}
}
},
{
$project: {
_id: false,
age: "$age",
phone: "$phone"
}
}
]);
The resulting output will be:
[
{
"age": 25,
"phone": "+12232325225"
}
]
In this final output, we’ve kept only the age and phone fields for users named “sohrab” with an age of 25.
Remember that $redact allows you to control the visibility of fields based on conditions, making it a valuable tool for fine-tuning your aggregation results.
Top comments (0)