

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1redact
<a name="redact"></a>

Amazon DocumentDB 中的`$redact`聚合阶段用于根据指定字段的值有选择地在输出文档中包含或排除内容。这在需要根据访问级别或用户权限控制敏感数据可见性的场景中特别有用。

**参数**
+ `$cond`：文档中每个字段的计算结果为`$$KEEP``$$PRUNE`、或`$$DESCEND`的表达式。
+ `$$KEEP`：保留输出文档中的当前字段。
+ `$$PRUNE`：从输出文档中移除当前字段。
+ `$$DESCEND`: 以递归方式将`$redact`舞台应用于当前字段，即对象或数组。

## 示例（MongoDB 外壳）
<a name="redact-examples"></a>

在此示例中，我们将使用`$redact`舞台根据订单的状态筛选订单，仅显示具有特定状态值的订单。

**创建示例文档**

```
db.orders.insert([
  { "_id": 1, "status": "shipped", "customer": "Carlos Salazar", "total": 150.00, "date": "2025-01-15" },
  { "_id": 2, "status": "processing", "customer": "Saanvi Sarkar", "total": 89.99, "date": "2025-01-20" },
  { "_id": 3, "status": "cancelled", "customer": "Zhang Wei", "total": 220.50, "date": "2025-01-18" }
])
```

**查询示例**

```
db.orders.aggregate([
  {
    $redact: {
      $cond: {
        if: { $in: ["$status", ["shipped", "processing"]] },
        then: "$$KEEP",
        else: "$$PRUNE"
      }
    }
  }
])
```

**输出**

```
[
  { _id: 1, status: 'shipped', customer: 'Carlos Salazar', total: 150, date: '2025-01-15' },
  { _id: 2, status: 'processing', customer: 'Saanvi Sarkar', total: 89.99, date: '2025-01-20' }
]
```

在此示例中，`$redact`舞台检查每个文档中`status`字段的值。如果`status`是 “已发货” 或 “处理中”，则保留文档 (`$$KEEP`)。否则，文档将被修剪 () `$$PRUNE`。

## 代码示例
<a name="redact-code"></a>

要查看使用该`$redact`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('orders');

  const result = await collection.aggregate([
    {
      $redact: {
        $cond: {
          if: { $in: ['$status', ['shipped', 'processing']] },
          then: '$$KEEP',
          else: '$$PRUNE'
        }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['orders']

    result = list(collection.aggregate([
        {
            '$redact': {
                '$cond': {
                    'if': { '$in': ['$status', ['shipped', 'processing']] },
                    'then': '$$KEEP',
                    'else': '$$PRUNE'
                }
            }
        }
    ]))

    print(result)
    client.close()

example()
```

------