实施字段级别修订

在本页面

$redact管道运算符根据存储在文档本身中的信息来限制文档的内容。

要存储访问条件数据,请在文档和嵌入文档中添加一个字段。要允许对同一数据的访问级别进行多种组合,请考虑将访问字段设置为数组数组。每个数组元素包含一个必需的集合,该集合允许具有该集合的用户访问数据。

然后,将$redact阶段包括在db.collection.aggregate()操作中,以基于查看数据所需的访问权限来限制结果集的内容。

有关$redact管道运算符的更多信息,包括其语法和关联的系统变量以及其他示例,请参见$redact

Procedure

例如,一个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" ] ]
       }
     ]
}
首页