文档菜单
文档首页
/
MongoDB 手册
/ / /

$redact (聚合)

在本页

  • 定义
  • 示例
$redact

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

Diagram of security architecture with middleware and redaction.

$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"
}
}
}
]
);

聚合操作返回以下“已编辑”文档:

{
"_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."
}
]
}

提示:

另请参阅:

  • $size

  • $setIntersection

集合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

提示:

另请参阅:

实现字段级别编辑,以设置相同数据的多个访问组合。

返回

切换日志输出

在本页