MongoDB ACL with Aggregation Framework using $redact

db.employees.insertOne(
{
acl:
[
"HR",
"Management",
"Finance",
"Executive"
],
employee_compensation:
{
acl:
[
"Management",
"Finance",
"Executive"
],
salary: 122519,
stock_award: 4880,
programs:
{
acl:
[
"Finance",
"Executive"
],
"401K_contrib": 0,
health_plan: true,
spp: 0.05
}
},
employee_grade: 3,
age: 50,
first_name: "Brown",
last_name: "Christian",
}
)
const $redact =
{
$cond:
[
{ $in: ['Management', '$acl'] },
'$$DESCEND',
'$$PRUNE'
]
}
  1. If acl field contains 'Management', then retain all the fields except for subdocuments and array of documents.
  2. Else, exclude all fields at this current document level without further inspection of any of the excluded fields regardless whether or not those fields have the correct access level.
db.employees.aggregate(
[
{ $redact }
]
)
[
{
"_id": {"$oid": "60f0695788aa7faa9cdb042c"},
"acl":
[
"HR",
"Management",
"Finance",
"Executive"
],
"employee_compensation": {
"acl":
[
"Management",
"Finance",
"Executive"
],
"salary": 122519,
"stock_award": 4880
},
"employee_grade": 3,
"age": 50,
"first_name": "Brown",
"last_name": "Christian",
}
]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ömer Toraman

Ömer Toraman

TypeScript developer working with React Native and Serverless applications