==============================================
MongoDB\\Database::createEncryptedCollection()
==============================================

.. versionadded:: 1.16

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

.. phpmethod:: MongoDB\\Database::createEncryptedCollection()

   Explicitly creates an encrypted collection.

   .. code-block:: php

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

   This method will automatically create data keys for any encrypted fields
   where ``keyId`` is ``null``. Data keys will be created using
   :php:`MongoDB\\Driver\\ClientEncryption::createDataKey() <mongodb-driver-clientencryption.createdatakey>`
   and the provided ``$kmsProvider`` and ``$masterKey`` parameters. A copy of
   the modified ``encryptedFields`` option will be returned in addition to the
   result from creating the collection.

   This method does not affect any auto encryption settings on existing
   :phpclass:`MongoDB\\Client` objects. Users must configure auto encryption
   after creating the encrypted collection with ``createEncryptedCollection()``.

   This method has the following parameters:

   .. include:: /includes/apiargs/MongoDBDatabase-method-createEncryptedCollection-param.rst

   The ``$options`` parameter supports the same options as
   :phpmethod:`MongoDB\\Database::createCollection()`. The ``encryptedFields``
   option is required.

Return Values
-------------

A tuple (i.e. two-element array) containing the result document from the
:manual:`create </reference/command/create>` command (an array or object
according to the ``typeMap`` option) and the modified ``encryptedFields``
option.

Errors/Exceptions
-----------------

:phpclass:`MongoDB\\Exception\\CreateEncryptedCollectionException` if any error
is encountered creating data keys or the collection. The original exception and
modified ``encryptedFields`` option can be accessed via the ``getPrevious()``
and ``getEncryptedFields()`` methods, respectively.

.. include:: /includes/extracts/error-invalidargumentexception.rst

Example
-------

The following example creates an encrypted ``users`` collection in the ``test``
database. The ``ssn`` field within the ``users`` collection will be defined as
an encrypted string field.

.. code-block:: php

   <?php

   // 96-byte master key used to encrypt/decrypt data keys
   define('LOCAL_MASTERKEY', '...');

   $client = new MongoDB\Client;

   $clientEncryption = $client->createClientEncryption([
       'keyVaultNamespace' => 'keyvault.datakeys',
       'kmsProviders' => [
           'local' => ['key' => new MongoDB\BSON\Binary(base64_decode(LOCAL_MASTERKEY), 0)],
        ],
   );

   [$result, $encryptedFields] = $client->test->createEncryptedCollection(
       'users',
       $clientEncryption,
       'local',
       null,
       [
           'encryptedFields' => [
               'fields' => [
                   ['path' => 'ssn', 'bsonType' => 'string', 'keyId' => null],
               ],
           ],
       ]
   );

If the encrypted collection was successfully created, ``$result`` will contain
the response document from the ``create`` command and
``$encryptedFields['fields'][0]['keyId']`` will contain a
:php:`MongoDB\\BSON\\Binary <class.mongodb-bson-binary>` object with subtype 4
(i.e. UUID).

The modified ``encryptedFields`` option can then be used to construct a new
:phpclass:`MongoDB\\Client` with auto encryption enabled.

.. code-block:: php

   <?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,
                ],
           ],
       ]
   );

See Also
--------

- :phpmethod:`MongoDB\\Database::createCollection()`
- :phpmethod:`MongoDB\\Client::createClientEncryption()`
- :php:`MongoDB\\Driver\\ClientEncryption::createDataKey() <mongodb-driver-clientencryption.createdatakey>`
- :manual:`create </reference/command/create>` command reference in the MongoDB
  manual
