Docs Menu
Docs Home
/ /

db.createEncryptedCollection() (mongosh method)

New in version 7.0.

db.createEncryptedCollection(collName, options)

db.createEncryptedCollection() creates an encrypted collection specified by collName on the current database.

This method is a wrapper around ClientEncryption.createEncryptedCollection() that automatically creates data keys if encryptedFields.fields[*].keyId is null or omitted in the options.createCollectionOptions.encryptedFields definition.

This command is available in deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

db.createEncryptedCollection() has the following syntax:

db.createEncryptedCollection(
collName,
{
provider: kmsProviderName,
createCollectionOptions: encryptedFieldsMap,
masterKey: customerMasterKeyCredentials
}
)

db.createEncryptedCollection() takes these fields:

Field
Type
Necessity
Description

collName

string

Required

Name of the collection to encrypt on the current database.

options

document

Required

Options to configure the encrypted collection.

options.provider

string

Required

KMS you are using to store your Customer Master Key.

options.createCollectionOptions

document

Required

Fields to encrypt. Must contain an encryptedFields document. See Steps for details on how to configure the encryptedFields document.

options.masterKey

document

Optional

Specifies the credentials and key identification fields needed to access the master key when the KMS Provider is AWS, GCP, or Azure. Optional when the KMS Provider is local.

The mongosh client-side field level and queryable encryption methods require a database connection configured for client-side encryption. If the current database connection was not initiated with client-side field level encryption enabled, either:

or

The db.createEncryptedCollection() method runs in the context of the current db and uses the same Queryable Encryption-enabled connection as the current mongosh session. Internally, it calls ClientEncryption.createEncryptedCollection() with the current database name, the specified collection name, and the provided options document.

When options.createCollectionOptions.encryptedFields.fields[*].keyId is null or omitted, the method automatically creates the required data keys in the key vault and populates the corresponding keyId values in the created collection's encryptedFields definition.

The following example uses a locally managed KMS for the Queryable Encryption configuration.

1
  1. Start mongosh

    Run:

    mongosh --nodb

    --nodb means don't connect to a database.

  2. Generate a Key String

    Generate a base 64 96-byte string:

    const TEST_LOCAL_KEY = require("crypto").randomBytes(96).toString("base64")
  3. Create an Encryption Options Object

    To create a client-side field level encryption options object, use the TEST_LOCAL_KEY string from the previous step:

    var autoEncryptionOpts = {
    "keyVaultNamespace" : "encryption.__dataKeys",
    "kmsProviders" : {
    "local" : {
    "key" : BinData(0, TEST_LOCAL_KEY)
    }
    }
    }
  4. Create an Encrypted Client Object

    To create an encrypted client object, use the Mongo() constructor. Replace the mongodb://myMongo.example.net URI with the connection string URI for the target cluster. For example:

    encryptedClient = Mongo(
    "mongodb://myMongo.example.net:27017/?replSetName=myMongo",
    autoEncryptionOpts
    )
2

Create an encryptedFieldsMap to specify which fields to encrypt:

const encryptedFieldsMap = {
encryptedFields: {
fields: [
{
path: "secretField",
bsonType: "string",
queries: { queryType: "equality" },
// keyId omitted; db.createEncryptedCollection() generates it
},
],
},
};
3

Create an encrypted enc.users collection using the helper on the current database:

const encDb = encryptedClient.getDB("enc");
let result = encDb.createEncryptedCollection(
"users",
{
provider: "local",
createCollectionOptions: encryptedFieldsMap,
masterKey: {} // masterKey is optional when provider is local
}
);
4

db.createEncryptedCollection() returns a result object that includes the created collection name and the collection's encryptedFields definition.

Check the value of result.collection to confirm the collection was created in the desired location, and optionally inspect the populated encryptedFields:

enc> result.collection
enc.users
enc> result.encryptedFields
{
fields: [
{
path: "secretField",
bsonType: "string",
queries: { queryType: "equality", /* ... */ },
keyId: UUID("...")
}
]
}
  • For complete documentation on initiating MongoDB connections with client-side field level encryption enabled, see Mongo().

  • For a complete example of how to create and query an encrypted collection, see Queryable Encryption Quick Start.

Back

db.createCollection

On this page