Mongo() (original) (raw)

Mongo(host, autoEncryptionOpts, api)

JavaScript constructor to instantiate a database connection frommongosh or from a JavaScript file.

The Mongo() method has the following parameters:

Parameter Type Description
host string or Mongo instance Optional. Host or connection string.The host can either be a connection string or in the form of or<:port>. The connection string can be in the form of a Mongo instance. If you specify a Mongo instance, theMongo() constructor uses the connection string of the specified Mongo instance.If omitted, Mongo() instantiates a connection to the localhost interface on the default port 27017.
autoEncryptionOpts document Optional. Configuration parameters for enablingIn-Use Encryption.autoEncryptionOpts overrides the existing in-use encryption configuration of the database connection. If omitted, Mongo()inherits the in-use encryption configuration of the current database connection.See AutoEncryptionOpts for usage and syntax details.
api document Optional. Configuration options for enabling theStable API.See api for usage and syntax details.

See also:

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

The autoEncryptionOpts document specifies configuration options for In-Use Encryption. If your database connection has an existing in-use encryption configuration,autoEncryptionOpts overrides that configuration. MongoDB provides two approaches to In-Use Encryption: Client-Side Field Level Encryption and Queryable Encryption.

For example, starting mongoshwith client-side field level encryption command-line options enables client-side encryption for that connection. New database connections created using Mongo() inherit the encryption settings unless Mongo() includes autoEncryptionOpts.

The autoEncryptionOpts document has the following syntax:


{

  "keyVaultClient" : <object>,

  "keyVaultNamespace" : "<string>",

  "kmsProviders" : <object>,

  "schemaMap" : <object>,

  "bypassAutoEncryption" : <boolean>,

  "tlsOptions": <object>,

  "encryptedFieldsMap": <object>

}

The autoEncryptionOpts document takes the following parameters:

Parameter Type Description
keyVaultClient Mongo() connection object. (Optional) The MongoDB cluster hosting the key vault collection.Specify a Mongo() connection object pointing to the cluster:var keyVaultClient = Mongo();var autoEncryptionOptions = { "keyVaultClient" : keyVaultClient, "keyVaultNamespace" : ".", "kmsProviders" : { ... }}If keyVaultClient is omitted, the host specified to theMongo() object containing theautoEncryptionOpts document is used as the key vault host.
keyVaultNamespace string (Required) The full namespace of the key vault collection.
kmsProviders document (Required) The Key Management Service (KMS) used by client-side field level encryption for managing a Customer Master Key (CMK). Client-side field level encryption uses the CMK for encrypting and decrypting data encryption keys.Client-Side Field Level Encryption supports the following KMS providers:Amazon Web Services KMSAzure Key VaultGoogle Cloud Platform KMSLocally Managed KeyIf possible, consider defining the credentials provided inkmsProviders as environment variables, and then passing them to mongosh using the --eval option. This minimizes the chances of credentials leaking into logs. See Create a Data Key for examples of this approach for each supported KMS.Amazon Web Services KMSIMPORTANT: For AWS KMS support, use mongosh, or the MongoDB 4.2.2 or later legacy mongo shell. The 4.2.0 and 4.2.1 legacy mongo shell do not support the AWS KMS service due to an unexpected change in the KMS response object. SeeSERVER-44721 for more information.Specify the aws document to kmsProviders with the following fields:"kmsProviders" : { "aws" : { "accessKeyId" : "AWSAccessKeyId", "secretAccessKey" : "AWSSecretAccessKey" } }The specified accessKeyId must correspond to an IAM user with all List and Read permissions for the KMS service.In some environments, the AWS SDK can pick up credentials automatically. To enable AWS KMS usage without providing explicit credentials to the AWS SDK, you can pass thekmsProvider details to the Mongo() constructor.{ "kmsProviders" : { "aws" : { } }}Azure Key VaultSpecify the azure document to kmsProviders with the following fields:"kmsProviders" : { "azure" : { "tenantId" : "AzureTenantId", "clientId" : "AzureClientId", "clientSecret" : "AzureClientSecret" }}New in version 5.0.Google Cloud KMSSpecify the gcp document to kmsProviders with the following fields:"kmsProviders" : { "gcp" : { "email" : "GCPEmail", "privateKey" : "GCPPrivateKey" }}New in version 5.0.Locally Managed KeySpecify the local document to kmsProviders with the following field:"kmsProviders" : { "local" : { "key" : BinData(0, "<96 byte base-64 encoded key>") }}The specified key must be a base64-encoded 96-byte string with no newline characters.
schemaMap document (Optional) The automatic client-side field level encryption rules specified using the JSON schema Draft 4 standard syntax and encryption-specific keywords. This option is mutually exclusive with explicitEncryptionOnly. If a collection is present on both theschemaMap and the encryptedFieldsMap, libmongocrypt errors on initialization.For complete documentation, seeEncryption Schemas.
bypassAutoEncryption boolean (Optional) Specify true to bypass automatic client-side field level encryption rules and perform explicit (manual) per-field encryption.
bypassQueryAnalysis boolean (Optional) Specify true to use explicit encryption on indexed fields without the crypt_shared library. For details, see MongoClient Options for Queryable Encryption.
explicitEncryptionOnly boolean (Optional) Specify true to use neither automatic encryption nor automatic decryption. You can use getKeyVault() andgetClientEncryption() to perform explicit encryption. This option is mutually exclusive with schemaMap. If omitted, defaults to false.
tlsOptions object (Optional) The path to the TLS client certificate and private key file in PEM format (tlsCertificateKeyFile), TLS client certificate and private key file password (tlsCertificateKeyFilePassword), or TLS certificate authority file (tlsCAFile) to use to connect to the KMS in PEM format. To learn more about these options, seeTLS Options.
encryptedFieldsMap document (Optional) The map of collection namespaces to encryptedFields documents.encryptedFields is a BSON document that describes the Queryable Encryption encrypted fields. If a collection is present on both theschemaMap and the encryptedFieldsMap, libmongocrypt errors on initialization.To learn more about encrypted fields in Queryable Encryption, seeEncrypted Fields and Enabled Queries.

The api parameter specifies configuration options for theStable API. You can enable or disable optional behavior using the following options:

Option Type Description
version string Specifies the API Version. "1" is currently the only supported version.
strict boolean If true:Using a command that is not part of the declared API version returns an APIStrictErrorerror.Indexes that are unsupportedby the Stable API are ignored by thequery planner.If you specify strict, you must also specify version.If not specified, defaults to false.
deprecationErrors boolean If true, using a command or behavior that is deprecated in the specified API version returns anAPIDeprecationError. If you specifydeprecationErrors, you must also specify version.If not specified, defaults to false.

The api parameter has the following syntax:


{ api: { version: <string>, strict: <boolean>, deprecationErrors: <boolean> } }

The following operation creates a new connection object from within amongosh session:


cluster = Mongo("mongodb://mymongo.example.net:27017/?replicaSet=myMongoCluster")

Issue operations against the cluster object to interact with themymongo.example.net:27017 cluster:


myDB = cluster.getDB("myDB"); //returns the database object

myColl = myDB.getCollection("myColl"); // returns the collection object

Start the mongosh client.

To configure client-side field level encryption for a locally managed key, generate a base64-encoded 96-byte string with no line breaks.


const TEST_LOCAL_KEY = require("crypto").randomBytes(96).toString("base64")

Create the client-side field level encryption options using the generated local key string:


 var autoEncryptionOpts = {

   "keyVaultNamespace" : "encryption.__dataKeys",

   "kmsProviders" : {

     "local" : {

       "key" : BinData(0, TEST_LOCAL_KEY)

     }

   }

 }

Use the Mongo() constructor with the client-side field level encryption options configured to create a database connection. Replace the mongodb://myMongo.example.net URI with the connection string URI of the target cluster.


encryptedClient = Mongo(

  "mongodb://myMongo.example.net:27017/?replSetName=myMongo",

   autoEncryptionOpts

)

Issue operations against the cluster object to interact with themymongo.example.net:27017 cluster and perform explicit encryption:


// returns the database object

myDB = cluster.getDB("myDB");

// returns the collection object

myColl = myDB.getCollection("myColl");

// returns object for managing data encryption keys

keyVault = cluster.getKeyVault();

// returns object for explicit encryption/decryption

clientEncryption = cluster.getClientEncryption();

See Client-Side Field Level Encryption Methods for a complete list of client-side field level encryption methods.

To configure client-side field level encryption for a locally managed key:


export TEST_LOCAL_KEY=$(echo "$(head -c 96 /dev/urandom | base64 | tr -d '\n')")

mongosh --nodb

The following operation creates a new connection object from within amongosh session. TheAutoEncryptionOpts option specifies the required options for enabling automatic client-side encryption on the hr.employees collection:


var autoEncryptionOpts = {

  "keyVaultNamespace" : "encryption.__dataKeys",

  "kmsProviders" : {

    "local" : {

      "key" : BinData(0, process.env["TEST_LOCAL_KEY"])

    }

  },

  schemaMap : {

    "hr.employees" : {

      "bsonType": "object",

      "properties" : {

        "taxid" : {

          "encrypt" : {

            "keyId" : [UUID("bffb361b-30d3-42c0-b7a4-d24a272b72e3")],

            "bsonType" : "string",

            "algorithm" : "AEAD_AES_256_CBC_HMAC_SHA_512-Random"

          }

        },

        "taxid-short": {

          "encrypt": {

            "keyId": [UUID("33408ee9-e499-43f9-89fe-5f8533870617")],

            "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",

            "bsonType": "string"

          }

        }

      }

    }

  }

}

cluster = Mongo(

  "mongodb://mymongo.example.net:27017/?replicaSet=myMongoCluster",

  autoEncryptionOpts

)

Issue operations against the cluster object to interact with themymongo.example.net:27017 cluster and utilize automatic encryption:


// returns the database object

myDB = cluster.getDB("myDB");

// returns the collection object

myColl = myDB.getCollection("myColl");

myColl.insertOne(

  {

    "name" : "J Doe",

    "taxid" : "123-45-6789",

    "taxid-short" : "6789"

  }

)

The specified automatic encryption rules encrypt the taxid andtaxid-short fields using the specified data encryption key and algorithm. Only clients configured for the correct KMS and access to the specified data encryption key can decrypt the field.

The following operation creates a new connection object from within amongosh session. The mongo.tlsOptions option enables a connection using KMIP as the KMS provider:


var csfleConnection = {

  keyVaultNamespace: "encryption.__keyVault",

  kmsProviders: { kmip: { endpoint: "kmip.example.com:123" } },

  tlsOptions: { kmip: { tlsCertificateKeyFile: "/path/to/client/cert-and-key-bundle.pem" } }

}

cluster = Mongo(

  "mongodb://mymongo.example.net:27017/?replicaSet=myMongoCluster",

  csfleConnection

);

See Client-Side Field Level Encryption Methods for a complete list of client-side field level encryption methods.

The following operation creates a new connection object from within amongosh session. The api option enables Stable API V1 and specifies that you cannot run deprecated command or commands outside of the Stable API.


cluster = Mongo(

  "mongodb://mymongo.example.net:27017/?replicaSet=myMongoCluster",

   null,

   { api: { version: "1", strict: true, deprecationErrors: true } }

)

To interact with the mymongo.example.net:27017 cluster, issue operations against the cluster object. For a full list of Stable API commands, see Stable API Commands.