Docs HomeMongoDB Manual

Mongo()

Description描述

Changed in version 4.2.4.2版更改。

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描述
hoststringOptional. 可选的。The host, either in the form of <host> or <host><:port>.主机,形式为<host><host><:port>
If omitted, Mongo() instantiates a connection to the localhost interface on the default port 27017. 如果省略,Mongo()将实例化到默认端口27017上的localhost接口的连接。
autoEncryptionOptsdocument New in version 4.2. 4.2版新增。
Optional. 可选的。Configuration parameters for enabling Client-Side Field Level Encryption.用于启用客户端字段级加密的配置参数。
autoEncryptionOpts overrides the existing client-side field level encryption configuration of the database connection. 覆盖数据库连接的现有客户端字段级加密配置。If omitted, Mongo() inherits the client-side field level encryption configuration of the current database connection.如果省略,Mongo()将继承当前数据库连接的客户端字段级加密配置。
See AutoEncryptionOpts for usage and syntax details. 有关用法和语法的详细信息,请参阅AutoEncryptionOpts
apidocumentOptional. 可选的。Configuration options for enabling the Stable API.用于启用稳定API的配置选项。
See api for usage and syntax details. 有关用法和语法的详细信息,请参阅api
Tip

See also: 另请参阅:

Mongo.getDB() and db.getMongo()

AutoEncryptionOpts

New in version 4.2. 4.2版新增。

The autoEncryptionOpts document specifies configuration options for Client-Side Field Level Encryption. autoEncryptionOpts文档指定客户端字段级加密的配置选项。If the database connection has an existing client-side field level encryption configuration, specifying autoEncryptionOpts overrides that configuration.如果数据库连接具有现有的客户端字段级加密配置,则指定autoEncryptionOpts将覆盖该配置。

For example, starting mongosh with client-side field level encryption command-line options enables client-side encryption for that connection. 例如,使用客户端字段级加密命令行选项启动mongosh可以为该连接启用客户端加密。New database connections created using Mongo() inherit the encryption settings unless Mongo() includes autoEncryptionOpts.使用Mongo()创建的新数据库连接将继承加密设置,除非Mongo()包含autoEncryptionOpts

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

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

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()对象指定的host将用作键保管库主机。
keyVaultNamespacestringRequired.必要的。The full namespace of the key vault collection.键保管库集合的完整命名空间
kmsProvidersdocumentRequired.必要的。 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
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. 4.2.0和4.2.1遗留mongo shell不支持AWS KMS服务,因为KMS响应对象发生了意外更改。See SERVER-44721 for more information. 有关更多信息,请参阅SERVER-44721
Specify the aws document to kmsProviders with the following fields: 使用以下字段指定aws文档到kmsProviders
"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用户相对应。
Azure Key Vault
Specify the azure document to kmsProviders with the following fields: 使用以下字段将azure文档指定给kmsProviders
"kmsProviders" : {
"azure" : {
"tenantId" : "AzureTenantId",
"clientId" : "AzureClientId",
"clientSecret" : "AzureClientSecret"
}
}

New in version 5.0. 5.0版新增。
Google Cloud 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. 指定的key必须是一个base64编码的96字节字符串,不包含换行符。
schemaMapdocumentOptional.可选的。The automatic client-side field level encryption rules specified using the JSON schema Draft 4 standard syntax and encryption-specific keywords.使用JSON模式Draft 4标准语法和加密特定键指定的自动客户端字段级加密规则。
For complete documentation, see Encryption Schemas.有关完整的文档,请参阅加密架构
bypassAutoEncryptionbooleanOptional.可选的。Specify true to bypass automatic client-side field level encryption rules and perform explicit (manual) per-field encryption.指定true可绕过自动客户端字段级加密规则并执行显式(手动)每个字段加密。
bypassQueryAnalysisbooleanOptional.可选的。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选项

api

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

Option选项Type类型Description描述
versionstringSpecifies the API Version. 指定API版本。"1" is currently the only supported version.是当前唯一受支持的版本。
strictbooleanIf true, using a command that is not part of the declared API version returns an APIStrictError error. 如果为true,则使用不是声明的API版本的一部分的命令将返回APIStrictError错误。If you specify strict, you must also specify version.如果指定strict,则还必须指定version
If not specified, defaults to false. 如果未指定,则默认为false
deprecationErrorsbooleanIf true, using a command or behavior that is deprecated in the specified API version returns an APIDeprecationError. 如果为true,则使用指定API版本中不推荐使用的命令或行为将返回APIDeprecationErrorIf you specify deprecationErrors, you must also specify version.如果指定depositionErrors,则还必须指定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 Client-Side Field Level 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和对指定数据加密键的访问权限配置的客户端才能解密该字段。

See Client-Side Field Level 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. 以下操作从mongosh会话中创建一个新的连接对象。The api option enables Stable API V1 and specifies that you cannot run deprecated command or commands outside of the Stable API.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命令