- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $redact (aggregation)
$redact (aggregation)¶
On this page
Definition¶
-
$redact
¶ Restricts the contents of the documents based on information stored in the documents themselves.
The
$redact
stage has the following prototype form:The argument can be any valid expression as long as it resolves to $$DESCEND, $$PRUNE, or $$KEEP system variables. For more information on expressions, see Expressions.
System Variable Description $$DESCEND $redact
returns the fields at the current document level, excluding embedded documents. To include embedded documents and embedded documents within arrays, apply the$cond
expression to the embedded documents to determine access for these embedded documents.$$PRUNE $redact
excludes all fields at this current document/embedded document level, without further inspection of any of the excluded fields. This applies even if the excluded field contains embedded documents that may have different access levels.$$KEEP $redact
returns or keeps all fields at this current document/embedded document level, without further inspection of the fields at this level. This applies even if the included field contains embedded documents that may have different access levels.
Examples¶
The examples in this section use the
db.collection.aggregate()
helper provided in the 2.6 version
of the mongo
shell.
Evaluate Access at Every Document Level¶
A forecasts
collection contains documents of the following form
where the tags
field lists the different access values for that
document/embedded document level; i.e. a value of [ "G", "STLW" ]
specifies either "G"
or "STLW"
can access the data:
A user has access to view information with either the tag "STLW"
or
"G"
. To run a query on all documents with year 2014
for this
user, include a $redact
stage as in the following:
The aggregation operation returns the following “redacted” document:
See also
Exclude All Fields at a Given Level¶
A collection accounts
contains the following document:
In this example document, the level
field determines the access
level required to view the data.
To run a query on all documents with status A
and exclude all
fields contained in a document/embedded document at level 5
, include a
$redact
stage that specifies the system variable
"$$PRUNE"
in the then
field:
The $redact
stage evaluates the level
field to
determine access. If the level
field equals 5
, then exclude all
fields at that level, even if the excluded field contains embedded documents
that may have different level
values, such as the shipping_addr
field.
The aggregation operation returns the following “redacted” document:
The result set shows that the $redact
stage excluded
the field cc
as a whole, including the shipping_addr
field
which contained embedded documents that had level
field values equal to
3
and not 5
.
See also
Implement Field Level Redaction for steps to set up multiple combinations of access for the same data.