Docs Menu
Docs Home
/
MongoDB Manual
/ / / / /

Enabling Queryable Encryption when Creating Collections

On this page

  • Overview
  • Enable Queryable Encryption on a Collection

Enable Queryable Encryption at collection creation. You can't encrypt fields on documents that are already in a collection.

Important

Explicitly create your collection, rather than creating it implicitly with an insert operation. When you create a collection using createCollection(), MongoDB creates an index on the encrypted fields. Without this index, queries on encrypted fields may run slowly.

You can enable Queryable Encryption on fields in one of two ways. The following examples use Node.js to enable Queryable Encryption:

  • Pass the encryption schema, represented by the encryptedFieldsObject constant, to the client that the application uses to create the collection:

    const client = new MongoClient(uri, {
    autoEncryption: {
    keyVaultNameSpace: "<your keyvault namespace>",
    kmsProviders: "<your kms provider>",
    extraOptions: {
    cryptSharedLibPath: "<path to Automatic Encryption Shared Library>"
    },
    encryptedFieldsMap: {
    "<databaseName.collectionName>": { encryptedFieldsObject }
    }
    }
    ...
    await client.db("<database name>").createEncryptedCollection("<collection name>");
    }

    For more information on autoEncryption configuration options, see the section on MongoClient Options for Queryable Encryption.

  • Pass the encryption schema encryptedFieldsObject to createEncryptedCollection():

    await encryptedDB.createEncryptedCollection("<collection name>", {
    encryptedFields: encryptedFieldsObject
    });

    Tip

    Specify the encryptedFieldsObject when you create the collection, and also when you create a client to access the collection. This ensures that if the server's security is compromised, the information is still encrypted through the client.

Back

Create a Schema