Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$redact(聚合)

在此页面上

  • 定义
  • 举例
$redact

根据存储在文档本身中的信息,限制整个文档被输出或者文档中的内容被输出。

带有中间件和日志校订的安全体系结构图。

$redact阶段具有以下原型形式:

{ $redact: <expression> }

该参数可以是任何有效的表达式,只要它解析为 $$DESCEND$$PRUNE$$KEEP 系统变量即可。有关表达式的更多信息,请参阅表达式

系统变量
说明
$$DESCEND
$redact返回当前文档级别的字段,不包括嵌入式文档。要在数组中包含嵌入式文档和嵌入式文档,请将$cond表达式应用于嵌入式文档,以确定这些嵌入式文档的访问权限。
$$PRUNE
$redact会排除当前文档/嵌入式文档级别的所有字段,而不进一步检查任何已排除的字段。即使已排除的字段包含可能具有不同访问级别的嵌入式文档,这也适用。
$$KEEP
$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"
}
}
}
]
);

该聚合操作返回以下 "redacted" 文档:

{
"_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的文档/嵌入式文档中包含的所有字段,请包含在then字段中指定系统变量"$$PRUNE"$redact阶段:

db.accounts.aggregate(
[
{ $match: { status: "A" } },
{
$redact: {
$cond: {
if: { $eq: [ "$level", 5 ] },
then: "$$PRUNE",
else: "$$DESCEND"
}
}
}
]
);

$redact阶段会对level字段求值以确定访问权限。如果level字段等于5 ,则排除该级别的所有字段,即使已排除的字段包含可能具有不同level值的嵌入式文档(例如shipping_addr字段)。

该聚合操作返回以下 "redacted" 文档:

{
"_id" : 1,
"level" : 1,
"acct_id" : "xyz123",
"status" : "A"
}

结果集显示, $redact阶段排除了整个字段cc ,包括shipping_addr字段,该字段包含level字段值等于3而不是5的嵌入式文档。

提示

另请参阅:

实施字段级日志校订以了解为同一数据设置多种访问权限组合的步骤。

← $project(聚合)

在此页面上