对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

MongoDB\Database::createEncryptedCollection()

1.16版本新增。

MongoDB\Database::createEncryptedCollection()

显式创建加密collection。

function createEncryptedCollection( string $collectionName, MongoDB\Driver\ClientEncryption $clientEncryption, string $kmsProvider, ?array $masterKey, array $options): array

此方法将自动为 keyId 为 null 的任何加密字段创建数据密钥。将使用MongoDB\ 驱动程序\ClientEncryption::createDataKey() 以及提供的 $kmsProvider 和 $masterKey 参数创建数据密钥。除了创建集合的结果之外,还会返回修改后的 encryptedFields 选项的副本。

此方法不会影响现有MongoDB\Client对象上的任何自动加密设置。 使用createEncryptedCollection()创建加密集合后,用户必须配置自动加密。

$collectionName : 细绳
要创建的加密collection的名称。
$clientEncryption : MongoDB\ 驱动程序\ClientEncryption
用于创建数据密钥的 ClientEncryption 对象。
$kmsProvider : 细绳
KMS提供商(例如“local”、“Amazon Web Services”),用于加密新数据密钥。 这对应于MongoDB\ 驱动程序\ClientEncryption::createDataKey() 的 $kmsProvider 参数。
$masterKey : array|null

将用于加密新数据密钥的KMS特定密钥选项。 这对应于MongoDB\ 驱动程序\ClientEncryption::createDataKey() 的 masterKey 选项。

如果$kmsProvider为“local”,则应为null 。

$options : array

指定所需选项的数组。

$options参数支持与MongoDB\Database::createCollection()相同的选项。 encryptedFields选项是必需的。

包含修改后的 encryptedFields 选项的大量。

MongoDB\Exception\CreateEncryptedCollectionException如果在创建数据键或collection时遇到任何错误)。原始异常和修改后的encryptedFields选项可以分别通过getPrevious()和getEncryptedFields()方法访问。

MongoDB\Exception\InvalidArgumentException 用于与参数或选项解析相关的错误。

userstest以下示例在数据库中创建了一个加密的collection集合。users集合中的ssn字段将被定义为加密字符串字段。

<?php // 96-byte master key used to encrypt/decrypt data keysdefine('LOCAL_MASTERKEY', '...'); $client = new MongoDB\Client; $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'keyvault.datakeys', 'kmsProviders' => [ 'local' => ['key' => new MongoDB\BSON\Binary(base64_decode(LOCAL_MASTERKEY), 0)], ],); $encryptedFields = $client->test->createEncryptedCollection( 'users', $clientEncryption, 'local', null, [ 'encryptedFields' => [ 'fields' => [ ['path' => 'ssn', 'bsonType' => 'string', 'keyId' => null], ], ], ]);

如果成功创建加密集合,则 $encryptedFields['fields'][0]['keyId'] 包含子类型为 4 (UUID) 的MongoDB\BSON\Binary对象。

然后,修改后的encryptedFields选项可用于构造启用自动加密的新MongoDB\Client 。

<?php $encryptedClient = new MongoDB\Client( null, // Connection string [], // Additional connection string options [ 'autoEncryption' => [ 'keyVaultNamespace' => 'keyvault.datakeys', 'kmsProviders' => [ 'local' => ['key' => new MongoDB\BSON\Binary(base64_decode(LOCAL_MASTERKEY), 0)], ], 'encryptedFieldsMap' => [ 'test.users' => $encryptedFields, ], ], ]);