实施字段级访问控制
在此页面上
$redact
管道操作符根据存储在文档中的信息限制文档内容。
要存储访问条件数据,请在这些文档和嵌入式文档中添加一个字段。要允许同一数据具有多种访问级别组合,请考虑将访问字段设置为数组的数组。每个数组元素包含一个所需的集合,以允许具有该集合的用户访问数据。
然后,在 db.collection.aggregate()
操作中包含 $redact
阶段,根据查看数据所需的访问权限限制结果集的内容。
有关 $redact
管道操作符的更多信息,包括其事务语法和相关系统变量以及其他示例,请参见 $redact
。
步骤
例如, forecasts
集合包含以下形式的文档,其中tags
字段确定查看数据所需的访问级别:
{ _id: 1, title: "123 Department Report", tags: [ [ "G" ], [ "FDW" ] ], year: 2014, subsections: [ { subtitle: "Section 1: Overview", tags: [ [ "SI", "G" ], [ "FDW" ] ], content: "Section 1: This is the content of section 1." }, { subtitle: "Section 2: Analysis", tags: [ [ "STLW" ] ], content: "Section 2: This is the content of section 2." }, { subtitle: "Section 3: Budgeting", tags: [ [ "TK" ], [ "FDW", "TGE" ] ], content: { text: "Section 3: This is the content of section3.", tags: [ [ "HCS"], [ "FDW", "TGE", "BX" ] ] } } ] }
对于每个文档,tags
字段包含查看数据所需的各种访问分组。 例如,值[ [ "G" ], [
"FDW", "TGE" ] ]
可以指定用户需要访问级别["G"]
或同时需要访问[ "FDW", "TGE" ]
才能查看数据。
假设用户只能查看带有 "FDW"
或 "TGE"
标签的信息。要对该用户 2014
年的所有文档运行查询,请添加 $redact
阶段,如下所示:
var userAccess = [ "FDW", "TGE" ]; db.forecasts.aggregate( [ { $match: { year: 2014 } }, { $redact: { $cond: { if: { $anyElementTrue: { $map: { input: "$tags" , as: "fieldTag", in: { $setIsSubset: [ "$$fieldTag", userAccess ] } } } }, then: "$$DESCEND", else: "$$PRUNE" } } } ] )
该聚合操作将返回用户的 "已编辑" 文档:
{ "_id" : 1, "title" : "123 Department Report", "tags" : [ [ "G" ], [ "FDW" ] ], "year" : 2014, "subsections" : [ { "subtitle" : "Section 1: Overview", "tags" : [ [ "SI", "G" ], [ "FDW" ] ], "content" : "Section 1: This is the content of section 1." }, { "subtitle" : "Section 3: Budgeting", "tags" : [ [ "TK" ], [ "FDW", "TGE" ] ] } ] }