Database Manual / Reference / mongosh Methods / Connections

Mongo() (mongosh method方法)

Description描述

Mongo(host, autoEncryptionOpts, api)

JavaScript constructor to instantiate a database connection from mongosh or from a JavaScript file.JavaScript构造函数,用于从mongosh或JavaScript文件实例化数据库连接。

The Mongo() method has the following parameters:Mongo()方法有以下参数:

Parameter参数Type类型Description描述
hoststring or Mongo instance字符串或Mongo实例

Optional. Host or connection string.可选。主机或连接字符串。

The host can either be a connection string or in the form of <host> or <host><:port>. 主机可以是连接字符串,也可以是<host><host><:port>的形式。The connection string can be in the form of a Mongo instance. 连接字符串可以是Mongo实例的形式。If you specify a Mongo instance, the Mongo() constructor uses the connection string of the specified Mongo instance.如果指定了Mongo实例,Mongo()构造函数将使用指定Mongo实例的连接字符串。

If omitted, Mongo() instantiates a connection to the localhost interface on the default port 27017.如果省略,Mongo()将在默认端口27017上实例化到localhost接口的连接。

autoEncryptionOptsdocument文档

Optional. Configuration parameters for enabling In-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.如果省略,Mongo()将继承当前数据库连接的正在使用的加密配置。

See AutoEncryptionOpts for usage and syntax details.有关用法和语法详细信息,请参阅AutoEncryptionOpts

apidocument文档

Optional. Configuration options for enabling the Stable API.可选。用于启用稳定API的配置选项。

See api for usage and syntax details.有关用法和语法的详细信息,请参阅api

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

AutoEncryptionOpts

The autoEncryptionOpts document specifies configuration options for In-Use Encryption. autoEncryptionOpts文档指定了正在使用的加密的配置选项。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.如果数据库连接有一个现有的正在使用的加密配置,autoEncryptionOpts会覆盖该配置。MongoDB提供了两种使用中加密的方法:客户端字段级加密和可查询加密

For example, starting mongosh with 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.例如,使用客户端字段级加密命令行选项启动mongosh可以为该连接启用客户端加密。使用Mongo()创建的新数据库连接继承加密设置,除非Mongo()包含autoEncryptionOpts

The autoEncryptionOpts document has the following syntax:autoEncryptionOpts文档具有以下语法:

{
"keyVaultClient" : <object>,
"keyVaultNamespace" : "<string>",
"kmsProviders" : <object>,
"schemaMap" : <object>,
"bypassAutoEncryption" : <boolean>,
"tlsOptions": <object>,
"encryptedFieldsMap": <object>
}

The autoEncryptionOpts document takes the following parameters:autoEncryptionOpts文档采用以下参数:

Parameter参数Type类型Description描述
keyVaultClientMongo() connection object.连接对象。

(Optional) The MongoDB cluster hosting the key vault collection.(可选)托管键保管库集合的MongoDB集群。

Specify a Mongo() connection object pointing to the cluster:指定一个指向集群的Mongo()连接对象:

var keyVaultClient = Mongo(<MongoDB URI>);

var autoEncryptionOptions = {
"keyVaultClient" : keyVaultClient,
"keyVaultNamespace" : "<database>.<collection>",
"kmsProviders" : { ... }
}

If keyVaultClient is omitted, the host specified to the Mongo() object containing the autoEncryptionOpts document is used as the key vault host.如果省略了keyVaultClient,则将为包含autoEncryptionOpts文档的Mongo()对象指定的主机用作键库主机。

keyVaultNamespacestring字符串(Required) (必填)The full namespace of the key vault collection.键保管库集合的完整命名空间
kmsProvidersdocument文档

(Required) The Key Management Service (KMS) used by client-side field level encryption for managing a Customer Master Key (CMK). (必需)客户端字段级加密用于管理客户主键(CMK)的键管理服务(KMS)Client-side field level encryption uses the CMK for encrypting and decrypting data encryption keys.客户端字段级加密使用CMK来加密和解密数据加密键。

Client-Side Field Level Encryption supports the following KMS providers:客户端字段级加密支持以下KMS提供程序:

If possible, consider defining the credentials provided in kmsProviders as environment variables, and then passing them to mongosh using the --eval option. 如果可能的话,考虑将kmsProviders中提供的凭据定义为环境变量,然后使用--eval选项将其传递给mongoshThis minimizes the chances of credentials leaking into logs. See Create a Data Key for examples of this approach for each supported KMS.这最大限度地减少了凭据泄露到日志中的可能性。有关每个受支持的KMS的此方法的示例,请参阅创建数据键

Amazon Web Services KMS亚马逊网络服务KMS

IMPORTANT: For AWS KMS support, use mongosh, or the MongoDB 4.2.2 or later legacy mongo shell. 对于AWS KMS支持,请使用mongosh或MongoDB 4.2.2或更高版本的遗留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. 由于KMS响应对象发生意外更改,4.2.0和4.2.1旧版mongo shell不支持AWS KMS服务。See SERVER-44721 for more information.有关更多信息,请参阅SERVER-44721

Specify the aws document to kmsProviders with the following fields:使用以下字段向kmsProviders指定aws文档:

"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.指定的accessKeyId必须对应于具有KMS服务的所有ListRead权限的IAM用户。

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 the kmsProvider details to the Mongo() constructor.在某些环境中,AWS SDK可以自动获取凭据。要在不向AWS SDK提供显式凭据的情况下启用AWS KMS使用,您可以将kmsProvider详细信息传递给Mongo()构造函数。

{
"kmsProviders" : { "aws" : { } }
}
Azure Key VaultAzure 键保管库

Specify the azure document to kmsProviders with the following fields:使用以下字段指定kmsProvidersazure文档:

"kmsProviders" : {
"azure" : {
"tenantId" : "AzureTenantId",
"clientId" : "AzureClientId",
"clientSecret" : "AzureClientSecret"
}
}

New in version 5.0.在版本5.0中新增。

Google Cloud KMS谷歌云KMS

Specify the gcp document to kmsProviders with the following fields:使用以下字段将gcp文档指定给kmsProviders

"kmsProviders" : {
"gcp" : {
"email" : "GCPEmail",
"privateKey" : "GCPPrivateKey"
}
}

New in version 5.0.在版本5.0中新增。

Locally Managed Key本地管理键

Specify the local document to kmsProviders with the following field:使用以下字段指定kmsProviderslocal文档:

"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.指定的键必须是base64编码的96字节字符串,没有换行符。

schemaMapdocument文档

(Optional) The automatic client-side field level encryption rules specified using the JSON schema Draft 4 standard syntax and encryption-specific keywords. (可选)使用JSON模式Draft 4标准语法和加密特定键指定的自动客户端字段级加密规则。This option is mutually exclusive with explicitEncryptionOnly. If a collection is present on both the schemaMap and the encryptedFieldsMap, libmongocrypt errors on initialization.此选项与explicitEncryptionOnly互斥。如果schemaMapencryptedFieldsMap上都存在集合,则初始化时libmongocrypt会出错。

For complete documentation, see Encryption Schemas.有关完整文档,请参阅加密模式

bypassAutoEncryptionboolean布尔值(Optional) Specify true to bypass automatic client-side field level encryption rules and perform explicit (manual) per-field encryption.(可选)指定true可绕过自动客户端字段级加密规则,并执行显式(手动)每个字段加密。
bypassQueryAnalysisboolean布尔值(Optional) Specify true to use explicit encryption on indexed fields without the crypt_shared library. (可选)指定true可在没有crypt_shared库的情况下对索引字段使用显式加密。For details, see MongoClient Options for Queryable Encryption.有关详细信息,请参阅MongoClient可查询加密选项
explicitEncryptionOnlyboolean布尔值(Optional) Specify true to use neither automatic encryption nor automatic decryption. (可选)指定true既不使用自动加密也不使用自动解密。You can use getKeyVault() and getClientEncryption() to perform explicit encryption. This option is mutually exclusive with schemaMap. If omitted, defaults to false.您可以使用getKeyVault()getClientEncryption()来执行显式加密。此选项与schemaMap互斥。如果省略,则默认为false
tlsOptionsobject(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. (可选)TLS客户端证书的路径;以及PEM格式的私钥文件(tlsCertificateKeyFile)、TLS客户端证书和私钥文件密码(tlsCCertificateKeyFilePassword)或TLS证书授权文件(tlsCAFile),用于连接PEM格式的KMS。To learn more about these options, see TLS Options.要了解有关这些选项的更多信息,请参阅TLS选项
encryptedFieldsMapdocument文档

(Optional) The map of collection namespaces to encryptedFields documents. encryptedFields is a BSON document that describes the Queryable Encryption encrypted fields. (可选)集合命名空间到encryptedFields文档的映射。encryptedFields是一个描述可查询加密加密字段的BSON文档。If a collection is present on both the schemaMap and the encryptedFieldsMap, libmongocrypt errors on initialization.如果schemaMapencryptedFieldsMap上都存在集合,则初始化时libmongocrypt会出错。

To learn more about encrypted fields in Queryable Encryption, see Encrypted Fields and Enabled Queries.要了解有关可查询加密中加密字段的更多信息,请参阅加密字段和已启用查询

api

The api parameter specifies configuration options for the Stable API. You can enable or disable optional behavior using the following options:api参数指定稳定api的配置选项。您可以使用以下选项启用或禁用可选行为:

Option选项Type类型Description描述
versionstring字符串Specifies the API Version. "1" is currently the only supported version.指定API版本。“1”是目前唯一受支持的版本。
strictboolean布尔值
If true:

If you specify strict, you must also specify version.若指定strict,则还必须指定version

If not specified, defaults to false.如果未指定,则默认为false

deprecationErrorsboolean布尔值

If true, using a command or behavior that is deprecated in the specified API version returns an APIDeprecationError. If you specify deprecationErrors, you must also specify version.如果为true,则使用指定API版本中不推荐使用的命令或行为将返回APIDeprecationError。如果指定deprecentErrors,则还必须指定version

If not specified, defaults to false.如果未指定,则默认为false

The api parameter has the following syntax:api参数具有以下语法:

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

Examples示例

Connect to a MongoDB Cluster连接到MongoDB集群

The following operation creates a new connection object from within a mongosh session:以下操作从mongosh会话中创建新的连接对象:

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

Issue operations against the cluster object to interact with the mymongo.example.net:27017 cluster:cluster对象发出操作以与mymongo.example.net:27017集群交互:

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

Connect to a Cluster with Client-Side Encryption Enabled连接到启用了客户端加密的群集

1

Start 启动mongosh

Start the mongosh client.启动mongosh客户端。

mongosh --nodb
2

Generate Your Key生成键

To configure client-side field level encryption for a locally managed key, generate a base64-encoded 96-byte string with no line breaks.要为本地管理的键配置客户端字段级加密,请生成一个没有换行符的base64编码的96字节字符串。

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

Create the Client-Side Field Level Encryption Options创建客户端字段级加密选项

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)
}
}
}
4

Create Your Encrypted Client创建加密客户端

Use the Mongo() constructor with the client-side field level encryption options configured to create a database connection. 使用Mongo()构造函数,并配置客户端字段级加密选项以创建数据库连接。Replace the mongodb://myMongo.example.net URI with the connection string URI of the target cluster.更换mongodb://myMongo.example.netURI与目标群集的连接字符串URI

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

Issue operations against the cluster object to interact with the mymongo.example.net:27017 cluster and perform explicit encryption:cluster对象发出操作以与mymongo.example.net:27017集群交互并执行显式加密:

// 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 In-Use Encryption Methods for a complete list of client-side field level encryption methods.有关客户端字段级加密方法的完整列表,请参阅正在使用的加密方法

Connect to a Cluster with Automatic Client-Side Encryption Enabled连接到启用了自动客户端加密的群集

To configure client-side field level encryption for a locally managed key:要为本地管理的键配置客户端字段级加密,请执行以下操作:

  • generate a base64-encoded 96-byte string with no line breaks生成一个没有换行符的base64编码的96字节字符串
  • use mongosh to load the key使用mongosh加载键
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 a mongosh session. 以下操作从mongosh会话中创建新的连接对象。The AutoEncryptionOpts option specifies the required options for enabling automatic client-side encryption on the hr.employees collection:AutoEncryptionOpts选项指定了在hr.employees集合上启用自动客户端加密所需的选项:

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 the mymongo.example.net:27017 cluster and utilize automatic encryption:cluster对象发出操作以与mymongo.example.net:27017集群交互,并使用自动加密:

// 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 and taxid-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.指定的自动加密规则使用指定的数据加密键和算法对taxidtaxid-short字段进行加密。只有为正确的KMS配置并访问指定数据加密键的客户端才能解密该字段。

The following operation creates a new connection object from within a mongosh session. The mongo.tlsOptions option enables a connection using KMIP as the KMS provider:以下操作从mongosh会话中创建新的连接对象。mongo.tlsOptions选项启用使用KMIP作为KMS提供程序的连接:

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 In-Use Encryption Methods for a complete list of client-side field level encryption methods.有关客户端字段级加密方法的完整列表,请参阅正在使用的加密方法

Connect to a Cluster with the Stable API Enabled连接到已启用稳定API的群集

The following operation creates a new connection object from within a mongosh session. The api option enables Stable API V1 and specifies that you cannot run deprecated command or commands outside of the Stable API.以下操作从mongosh会话中创建新的连接对象。api选项启用Stable api V1,并指定您不能在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.要与mymongo.example.net:27017集群交互,请对cluster对象执行操作。有关Stable API命令的完整列表,请参阅Stable API命令