$redact (聚合)
定义
示例
本节中的示例使用 db.collection.aggregate()
辅助函数。
在每份文档级别评估访问权限
forecasts
集合包含以下形式的文档,其中 tags
字段列出了该文档/嵌套文档级别的不同访问值;即 [ "G", "STLW" ]
指定 "G"
或 "STLW"
可以访问数据。
{ _id: 1, title: "123 Department Report", tags: [ "G", "STLW" ], year: 2014, subsections: [ { subtitle: "Section 1: Overview", tags: [ "SI", "G" ], 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" ], content: { text: "Section 3: This is the content of section 3.", tags: [ "HCS" ] } } ] }
用户可以使用标签“STLW
”或“G
”查看信息。要为此用户运行查询以检索所有年份为2014
的文档,请在以下方式中包含一个$redact
阶段:
var userAccess = [ "STLW", "G" ]; db.forecasts.aggregate( [ { $match: { year: 2014 } }, { $redact: { $cond: { if: { $gt: [ { $size: { $setIntersection: [ "$tags", userAccess ] } }, 0 ] }, then: "$$DESCEND", else: "$$PRUNE" } } } ] );
聚合操作返回以下“已编辑”文档:
{ "_id" : 1, "title" : "123 Department Report", "tags" : [ "G", "STLW" ], "year" : 2014, "subsections" : [ { "subtitle" : "Section 1: Overview", "tags" : [ "SI", "G" ], "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." } ] }
排除给定级别的所有字段
集合accounts
包含以下文档:
{ _id: 1, level: 1, acct_id: "xyz123", cc: { level: 5, type: "yy", num: 000000000000, exp_date: ISODate("2015-11-01T00:00:00.000Z"), billing_addr: { level: 5, addr1: "123 ABC Street", city: "Some City" }, shipping_addr: [ { level: 3, addr1: "987 XYZ Ave", city: "Some City" }, { level: 3, addr1: "PO Box 0123", city: "Some City" } ] }, status: "A" }
在此示例文档中,level
字段确定查看数据的所需访问级别。
要查询所有状态为A
的文档并排除文档/嵌套文档中位于级别5
的所有字段,请包含一个指定系统变量“"$$PRUNE"
”在then
字段的$redact
阶段:
db.accounts.aggregate( [ { $match: { status: "A" } }, { $redact: { $cond: { if: { $eq: [ "$level", 5 ] }, then: "$$PRUNE", else: "$$DESCEND" } } } ] );
$redact
阶段评估level
字段以确定访问权限。如果level
字段等于5
,则排除该级别的所有字段,即使排除的字段包含具有不同level
值的嵌套文档,例如shipping_addr
字段。
聚合操作返回以下“已编辑”文档:
{ "_id" : 1, "level" : 1, "acct_id" : "xyz123", "status" : "A" }
结果集显示$redact
阶段排除了字段cc
,包括包含嵌套文档的字段shipping_addr
,这些嵌套文档的level
字段值等于3
,而不是5
。