MongoDB 2.6 has an API that Restricts the contents of the documents based on information stored in the documents themselves.
Evaluates Access at Every Document/Sub-Document Level
A test collection contains documents of the following form where the tags field lists the different access values for that document/subdocument level; i.e. a value of [ “public", “internal" ] specifies either “public" or “internal" can access the data:
Sample Example JSON Document below
{
"_id" : 1,
"title" : "Document Formatting",
"tags" : [
"PUBLIC",
"SERVICE_PROVIDER",
"INTERNAL"
],
"year" : 2014,
"subsections" : [
{
"subtitle" : "Section 1: Overview",
"tags" : [
"PUBLIC",
"SERVICE_PROVIDER"
],
"content" : "Section 1: This is PUBLIC and SERVICE PROVIDER content of section 1."
},
{
"subtitle" : "Section 2: SuperScript",
"tags" : [
"SERVICE_PROVIDER"
],
"content" : "Section 2: This is SERVICE PROVIDER content of section 2."
},
{
"subtitle" : "Section 3: SubScript",
"tags" : [
"PUBLIC"
],
"content" : {
"text" : "Section 3: This is INTERNAL content of section3.",
"tags" : [
"INTERNAL"
]
}
}
]
}
A user has access to view information with either the tag “public" or “internal". To run a query on all documents with year 2014 for this user, include a $redact stage as in the following:
var userAccess = ["INTERNAL","PUBLIC"];
db.test.aggregate(
[
{ $match: { year: 2014 } },
{ $redact:
{
$cond:
{
if: { $gt: [ { $size: { $setIntersection: [ "$tags", userAccess ] } }, 0 ] },
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]
)
The aggregation operation returns the following “redacted” document, which does not include SERVICE_PROVIDER subsection.
{
"result" : [
{
"_id" : 1,
"title" : "Document Formatting",
"tags" : [
"PUBLIC",
"SERVICE_PROVIDER",
"INTERNAL"
],
"year" : 2014,
"subsections" : [
{
"subtitle" : "Section 1: Overview",
"tags" : [
"PUBLIC",
"SERVICE_PROVIDER"
],
"content" : "Section 1: This is PUBLIC and SERVICE PROVIDER content of section 1."
},
{
"subtitle" : "Section 3: SubScript",
"tags" : [
"PUBLIC"
],
"content" : {
"text" : "Section 3: This is INTERNAL content of section3.",
"tags" : [
"INTERNAL"
]
}
}
]
}
],
"ok" : 1
}