How to Read if (Std::cin >> )

This document describes the URI formats for defining connections between applications and MongoDB instances in the official MongoDB Drivers. For a list of drivers and links to driver documentation, see Drivers.

You can specify the MongoDB connection cord using either:

  • the Standard Connection String Format or
  • the DNS Seed List Connexion Format.

This section describes the standard format of the MongoDB connection URI used to connect to a MongoDB deployment: standalone, replica set, or a sharded cluster.

The standard URI connection scheme has the form:

                                      

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

For more than examples, see Examples.

The standard URI connection string includes the following components:

Component

Description

mongodb://

A required prefix to place that this is a cord in the standard connection format.

username:countersign@

Optional. Authentication credentials.

If specified, the client volition endeavor to authenticate the user to the authSource. If authSource is unspecified, the client will endeavour to authenticate the user to the defaultauthdb. And if the defaultauthdb is unspecified, to the admin database.

Note

If the username or password includes the post-obit characters:

                                                                              

: / ? # [ ] @

those characters must exist converted using percent encoding.

See likewise authSource.

host[:port]

The host (and optional port number) where the mongod instance (or mongos instance for a sharded cluster) is running. You tin specify a hostname, IP address, or UNIX domain socket. Specify every bit many hosts every bit appropriate for your deployment topology:

  • For a standalone, specify the hostname of the standalone mongod instance.
  • For a replica gear up, specify the hostname(s) of the mongod case(south) as listed in the replica set configuration.
  • For a sharded cluster, specify the hostname(s) of the mongos instance(s).

If the port number is not specified, the default port 27017 is used.

/defaultauthdb

Optional. The authentication database to use if the connexion string includes username:password@ authentication credentials but the authSource selection is unspecified.

If both authSource and defaultauthdb are unspecified, the client will endeavour to authenticate the specified user to the admin database.

?<options>

Optional. A query string that specifies connexion specific options as <name>=<value> pairs. Encounter Connectedness String Options for a full description of these options.

If the connectedness cord does non specify a database/ you must specify a slash (/) between the last host and the question mark (?) that begins the cord of options.

New in version 3.6.

In addition to the standard connection format, MongoDB supports a DNS-constructed seed list. Using DNS to construct the available servers list allows more flexibility of deployment and the ability to change the servers in rotation without reconfiguring clients.

In society to leverage the DNS seed list, use a connectedness string prefix of mongodb+srv rather than the standard mongodb. The +srv indicates to the client that the hostname that follows corresponds to a DNS SRV record. The commuter or mongosh will so query the DNS for the tape to decide which hosts are running the mongod instances.

Use of the +srv connection string modifier automatically sets the tls (or the equivalent ssl) option to true for the connection. You can override this behavior by explicitly setting the tls (or the equivalent ssl) option to simulated with tls=fake (or ssl=false) in the query string.

The following instance shows a typical connexion string for a DNS seed listing connection cord:

                                      

mongodb+srv://server.example.com/

The corresponding DNS configuration might resemble:

                                      
Record TTL Form Priority Weight Port Target
_mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27317 mongodb1.instance.com.
_mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27017 mongodb2.example.com.

When a client connects to a fellow member of the seed list, the client retrieves a list of replica set members it tin can connect to. Clients frequently apply DNS aliases in their seed lists which means the host may return a server listing that differs from the original seed listing. If this happens, clients will use the hostnames provided by the replica set rather than the hostnames listed in the seed list to ensure that replica set members tin can be reached via the hostnames in the resulting replica set up config.

The hostnames returned in SRV records must share the aforementioned parent domain (in this case, example.com) equally the given hostname. If the parent domains and hostname do non match, you will not be able to connect.

Like the standard connectedness string, the DNS seed list connexion string supports specifying options equally a query string. With a DNS seed list connection cord, y'all can also specify the post-obit options via a TXT record:

  • replicaSet
  • authSource

You may only specify one TXT record per mongod case. If multiple TXT records appear in the DNS and/or if the TXT record contains an option other than replicaSet or authSource, the client will return an error.

The TXT tape for the server.example.com DNS entry would resemble:

                                      
Record TTL Grade Text
server.example.com. 86400 IN TXT "replicaSet=mySet&authSource=authDB"

Taken together, the DNS SRV records and the options specified in the TXT record resolve to the post-obit standard format connection string:

                                      

mongodb://mongodb1.example.com:27317,mongodb2.instance.com:27017/?replicaSet=mySet&authSource=authDB

You can override the options specified in a TXT tape past passing the option in the query cord. In the following example, the query string has provided an override for the authSource selection configured in the TXT record of the DNS entry above.

                                      

mongodb+srv://server.case.com/?connectTimeoutMS=300000&authSource=aDifferentAuthDB

Given the override for the authSource, the equivalent connexion string in the standard format would be:

                                      

mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?connectTimeoutMS=300000&replicaSet=mySet&authSource=aDifferentAuthDB

The mongodb+srv option will fail if there is no available DNS with records that stand for to the hostname identified in the connection string. In addition, utilise of the +srv connection string modifier automatically sets the tls (or the equivalent ssl) option to true for the connection. You can override this behavior past explicitly setting the tls (or the equivalent ssl) option to simulated with tls=fake (or ssl=imitation) in the query string.

This department lists all connection options.

Connection options are pairs in the following form: proper name=value.

  • The pick name is case insensitive when using a driver.
  • The option proper noun is case insensitive when using mongosh, or the version iv.2 or later legacy mongo shell.
  • The option name is case sensitive when using a version iv.0 and earlier legacy mongo shell.
  • The value is ever case sensitive.

Divide options with the ampersand (i.e. &) character name1=value1&name2=value2. In the following example, a connection includes the replicaSet and connectTimeoutMS options:

                                  

mongodb://db1.example.net:27017,db2.example.internet:2500/?replicaSet=examination&connectTimeoutMS=300000

Semi-colon separator for connexion string arguments

To provide backwards compatibility, drivers currently accept semi-colons (i.e. ;) as option separators.

The post-obit connexion string to a replica fix named myRepl with members running on the specified hosts:

                                      

mongodb://db0.case.com:27017,db1.example.com:27017,db2.case.com:27017/?replicaSet=myRepl

Connection Option

Description

replicaSet

Specifies the name of the replica set, if the mongod is a member of a replica gear up.

When connecting to a replica set, provide a seed listing of the replica set member(s) to the host[:port] component of the uri. For specific details, refer to your driver documentation.

The following connection string to a replica gear up includes tls=true option (available starting in MongoDB 4.2):

                                          

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&tls=true

Alternatively, you tin can besides utilize the equivalent ssl=true option:

                                          

mongodb://db0.case.com,db1.example.com,db2.example.com/?replicaSet=myRepl&ssl=true

Connection Choice

Clarification

tls

Enables or disables TLS/SSL for the connectedness:

  • true: Initiate the connectedness with TLS/SSL. Default for DNS Seed List Connection Format.
  • fake: Initiate the connection without TLS/SSL. Default for Standard Connection String Format.

Note

The tls option is equivalent to the ssl choice.

If the mongo beat specifies boosted tls/ssl options from the command-line, use the --tls command-line option instead.

New in version 4.2.

ssl

A boolean to enable or disables TLS/SSL for the connection:

  • true: Initiate the connectedness with TLS/SSL. Default for DNS Seed List Connection Format.
  • false: Initiate the connection without TLS/SSL. Default for Standard Connection Cord Format.

Note

The ssl pick is equivalent to the tls option.

If the mongo beat specifies additional tls/ssl options from the command-line, use the --ssl command-line option instead.

tlsCertificateKeyFile

Specifies the location of a local .pem file that contains either the client's TLS/SSL X.509 certificate or the customer'southward TLS/SSL document and key.

The customer presents this file to the mongod/mongos instance.

Changed in version 4.four: mongod / mongos logs a warning on connection if the presented x.509 certificate expires within thirty days of the mongod/mongos host system time. Encounter x.509 Certificates Nearing Death Trigger Warnings for more than information.

This option is not supported by all drivers. Refer to the Drivers documentation.

This connexion string selection is non available for the mongo shell. Use the command-line pick instead.

New in version 4.two.

tlsCertificateKeyFilePassword

Specifies the password to de-crypt the tlsCertificateKeyFile.

This option is not supported by all drivers. Refer to the Drivers documentation.

This connection string choice is not bachelor for the mongo shell. Use the command-line option instead.

New in version 4.two.

tlsCAFile

Specifies the location of a local .pem file that contains the root certificate chain from the Document Authority. This file is used to validate the certificate presented past the mongod/mongos instance.

This option is not supported past all drivers. Refer to the Drivers documentation.

This connection string choice is not available for the mongo shell. Use the command-line option instead.

New in version 4.2.

tlsAllowInvalidCertificates

Bypasses validation of the certificates presented by the mongod/mongos instance

Set to true to connect to MongoDB instances even if the server'south present invalid certificates.

This pick is not supported by all drivers. Refer to the Drivers documentation.

This connectedness string option is not bachelor for the mongo shell. Use the command-line option instead.

Alarm

Disabling document validation creates a vulnerability.

New in version iv.two.

tlsAllowInvalidHostnames

Disables hostname validation of the certificate presented past the mongod/mongos instance.

Gear up to true to connect to MongoDB instances fifty-fifty if the hostname in the server certificates do not match the server's host.

This option is not supported past all drivers. Refer to the Drivers documentation.

This connexion string option is non available for the mongo trounce. Employ the command-line selection instead.

Alert

Disabling certificate validation creates a vulnerability.

New in version iv.two.

tlsInsecure

Disables various certificate validations.

Ready to true to disable certificate validations. The exact validatations disabled vary past drivers. Refer to the Drivers documentation.

This connection cord option is non available for the mongo beat out. Apply the command-line selection instead.

Warning

Disabling certificate validation creates a vulnerability.

New in version 4.2.

Connection Option

Clarification

connectTimeoutMS

The time in milliseconds to try a connexion earlier timing out. The default is never to timeout, though dissimilar drivers might vary. Run into the driver documentation.

socketTimeoutMS

The time in milliseconds to try a send or receive on a socket before the try times out. The default is never to timeout, though different drivers might vary. Run across the driver documentation.

Connexion Option

Clarification

compressors

Comma-delimited string of compressors to enable network compression for advice between this customer and a mongod/mongos instance.

You can specify the following compressors:

  • snappy
  • zlib (Bachelor in MongoDB 3.6 or greater)
  • zstd (Bachelor in MongoDB 4.2 or greater)

If you specify multiple compressors, so the social club in which you listing the compressors thing as well as the communication initiator. For example, if the customer specifies the following network compressors "zlib,snappy" and the mongod specifies "snappy,zlib", messages between the client and the mongod uses zlib.

Of import

Messages are compressed when both parties enable network pinch. Otherwise, messages between the parties are uncompressed.

If the parties do not share at least i mutual compressor, messages betwixt the parties are uncompressed.

mongosh supports the uri connection string option compressors.

zlibCompressionLevel

An integer that specifies the pinch level if using zlib for network compression.

You can specify an integer value ranging from -1 to 9:

Value

Notes

-ane

Default pinch level, usually level 6 compression.

0

No compression

1 - 9

Increasing level of compression but at the price of speed, with:

  • 1 providing the all-time speed but to the lowest degree compression, and
  • 9 providing the best pinch just at the slowest speed.

Non supported by mongosh.

Most drivers implement some kind of connection pool handling. Some drivers do not support connection pools. Come across your driver documentation for more information on the connection pooling implementation. These options permit applications to configure the connection pool when connecting to the MongoDB deployment.

Connection Option

Clarification

maxPoolSize

The maximum number of connections in the connectedness pool. The default value is 100.

minPoolSize

The minimum number of connections in the connectedness pool. The default value is 0.

Annotation

The minPoolSize option is not supported by all drivers. For information on your commuter, come across the Drivers documentation.

maxIdleTimeMS

The maximum number of milliseconds that a connection can remain idle in the pool before beingness removed and closed.

This pick is not supported past all drivers.

waitQueueMultiple

A number that the driver multiplies the maxPoolSize value to, to provide the maximum number of threads allowed to wait for a connection to become available from the pool. For default values, see the commuter documentation.

This option is not supported past all drivers.

waitQueueTimeoutMS

The maximum time in milliseconds that a thread can await for a connection to become available. For default values, see the commuter documentation.

This option is not supported by all drivers.

Write concern describes the level of acquittance requested from MongoDB. The write concern option is supported by the:

  • MongoDB drivers
  • mongosh
  • mongofiles
  • mongoimport
  • mongorestore

You can specify the write business organization both in the connection string and equally a parameter to methods like insert or update. If the write business organisation is specified in both places, the method parameter overrides the connection-cord setting.

The following connexion string to a replica set specifies "majority" write concern and a 5 2d timeout using the wtimeoutMS write business parameter:

                                      

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&w=majority&wtimeoutMS=5000

Connexion Option

Description

w

Corresponds to the write concern west Option. The w option requests acknowledgement that the write functioning has propagated to a specified number of mongod instances or to mongod instances with specified tags.

You lot tin can specify a number, the string majority, or a tag set.

For details, see due west Choice.

wtimeoutMS

Corresponds to the write concern wtimeout. wtimeoutMS specifies a time limit, in milliseconds, for the write concern.

When wtimeoutMS is 0, write operations volition never time out. For more information, see wtimeout.

journal

Corresponds to the write concern j Option choice. The journal option requests acknowledgement from MongoDB that the write functioning has been written to the journal. For details, see j Option.

If yous set up journal to true, and specify a w value less than 1, journal prevails.

If you ready journal to true, and the mongod does not accept journaling enabled, every bit with storage.journal.enabled, then MongoDB will error.

For more data, run into Write Concern.

New in version iii.2: For the WiredTiger storage engine, MongoDB 3.2 introduces the readConcern option for replica sets and replica set shards.

Read Concern allows clients to choose a level of isolation for their reads from replica sets.

The following connection cord to a replica fix specifies readConcernLevel=bulk:

                                      

mongodb://db0.example.com,db1.example.com,db2.case.com/?replicaSet=myRepl&readConcernLevel=majority

For more data, run across Read Business organization.

Read preferences describe the behavior of read operations with regards to replica sets. These parameters permit yous to specify read preferences on a per-connection ground in the connection string.

For instance:

  • The following connection string to a replica set specifies secondary read preference mode and a maxStalenessSeconds value of 120 seconds:

                                                  

    mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readPreference=secondary&maxStalenessSeconds=120

  • The following connection string to a sharded cluster specifies secondary read preference manner and a maxStalenessSeconds value of 120 seconds:

                                                  

    mongodb://mongos1.example.com,mongos2.example.com/?readPreference=secondary&maxStalenessSeconds=120

  • The following connection string to a sharded cluster specifies secondary read preference mode besides as three readPreferenceTags:

                                                  

    mongodb://mongos1.example.com,mongos2.example.com/?readPreference=secondary&readPreferenceTags=dc:ny,rack:r1&readPreferenceTags=dc:ny&readPreferenceTags=

Social club matters when using multiple readPreferenceTags. The readPreferenceTags are tried in lodge until a lucifer is found. Once constitute, that specification is used to find all eligible matching members and any remaining readPreferenceTags are ignored. For details, see Gild of Tag Matching.

Connection Selection

Description

readPreference

Specifies the read preferences for this connexion. Possible values are:

  • primary (Default)
  • primaryPreferred
  • secondary
  • secondaryPreferred
  • nearest

Multi-document transactions that contain read operations must use read preference primary. All operations in a given transaction must road to the same member.

This connection string option is not available for the mongo trounce. See cursor.readPref() and Mongo.setReadPref() instead.

maxStalenessSeconds

Specifies, in seconds, how stale a secondary can be earlier the client stops using it for read operations. For details, see Read Preference maxStalenessSeconds.

By default, in that location is no maximum staleness and clients will not consider a secondary's lag when choosing where to direct a read operation.

The minimum maxStalenessSeconds value is 90 seconds. Specifying a value betwixt 0 and 90 seconds volition produce an mistake. MongoDB drivers care for a maxStalenessSeconds value of -i every bit "no max staleness", the same as if maxStalenessSeconds is omitted.

Important

To use maxStalenessSeconds, all of the MongoDB instances in your deployment must be using MongoDB 3.iv or subsequently. If whatsoever instances are on an before version of MongoDB, the driver or mongod/mongos will raise an error.

New in version iii.4.

readPreferenceTags

Specifies the tags document as a comma-separated list of colon-separated key-value pairs. For example,

  • To specify the tags document { "dc": "ny", "rack": "r1" }, use readPreferenceTags=dc:ny,rack:r1 in the connexion string.
  • To specify an empty tags certificate { }, utilise readPreferenceTags= without setting the value.

To specify a list of tag documents, utilise multiple readPreferenceTags. For example, readPreferenceTags=dc:ny,rack:r1&readPreferenceTags=.

Gild matters when using multiple readPreferenceTags. The readPreferenceTags are tried in society until a match is found. For details, encounter Gild of Tag Matching.

This connection cord pick is not available for the mongo shell. Meet cursor.readPref() and Mongo.setReadPref() instead.

For more information, run across Read preferences.

The following connection string to a replica set up specifies the authSource to the admin database. That is, the user credentials are authenticated against the admin database.

                                      

mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl&authSource=admin

If the username or password includes the post-obit characters:

those characters must be converted using pct encoding.

Connexion Option

Description

authSource

Specify the database proper noun associated with the user's credentials. If authSource is unspecified, authSource defaults to the defaultauthdb specified in the connection string. If defaultauthdb is unspecified, then authSource defaults to admin.

The PLAIN (LDAP), GSSAPI (Kerberos), and MONGODB-AWS (IAM) hallmark mechanisms require that authSource be ready to $external, as these mechanisms delegate credential storage to external services.

MongoDB will ignore authSource values if no username is provided, either in the connection string or via the --username parameter.

authMechanism

Specify the authentication mechanism that MongoDB will use to authenticate the connection. Possible values include:

  • SCRAM-SHA-i
  • SCRAM-SHA-256 (Added in MongoDB 4.0)
  • MONGODB-X509
  • MONGODB-AWS (Added in MongoDB four.4)
  • GSSAPI (Kerberos)
  • Plain (LDAP SASL)

MongoDB 4.0 removes back up for the MONGODB-CR authentication mechanism. You cannot specify MONGODB-CR as the authentication mechanism when connecting to MongoDB 4.0+ deployments.

Only MongoDB Enterprise mongod and mongos instances provide GSSAPI (Kerberos) and PLAIN (LDAP) mechanisms.

To employ MONGODB-X509, you must accept TLS/SSL Enabled.

To utilize MONGODB-AWS, you must be connecting to a MongoDB Atlas cluster which has been configured to support authentication via AWS IAM credentials (i.e. an AWS access central ID and a secret admission primal, and optionally an AWS session token). The MONGODB-AWS authentication mechanism requires that the authSource be fix to $external.

When using MONGODB-AWS, provide your AWS access key ID as the username and the undercover access key as the countersign. If using an AWS session token likewise, provide it with the AWS_SESSION_TOKEN authMechanismProperties value.

Note

If the AWS access central ID, cloak-and-dagger access key, or session token include the following characters:

                                                                          

: / ? # [ ] @

those characters must be converted using pct encoding.

Alternatively, if the AWS access key ID, secret access key, or session token are divers on your platform using their corresponding AWS IAM environs variables mongosh will use these environment variable values to authenticate; you do not need to specify them in the connection string.

See Connect to an Atlas Cluster for case usage of the MONGODB-AWS hallmark machinery using both a connection cord and the environment variables method.

See Authentication for more than information near the authentication system in MongoDB. Also consider Apply x.509 Certificates to Authenticate Clients for more information on x509 authentication.

authMechanismProperties

Specify properties for the specified authMechanism equally a comma-separated list of colon-separated fundamental-value pairs.

Possible key-value pairs are:

SERVICE_NAME:<string>

Set the Kerberos service proper name when connecting to Kerberized MongoDB instances. This value must match the service proper name attack MongoDB instances to which you lot are connecting. Only valid when using the GSSAPI authentication mechanism.

SERVICE_NAME defaults to mongodb for all clients and MongoDB instances. If yous alter the saslServiceName setting on a MongoDB instance, you must set SERVICE_NAME to friction match that setting. Only valid when using the GSSAPI authentication machinery.

CANONICALIZE_HOST_NAME:true|false
Canonicalize the hostname of the client host machine when connecting to the Kerberos server. This may be required when hosts study different hostnames than what is in the Kerberos database. Defaults to faux. Only valid when using the GSSAPI authentication mechanism.
SERVICE_REALM:<cord>
Ready the Kerberos realm for the MongoDB service. This may be necessary to support cross-realm authentication where the user exists in ane realm and the service in another. Only valid when using the GSSAPI hallmark machinery.
AWS_SESSION_TOKEN:<security_token>
Set the AWS session token for authentication with temporary credentials when using an AssumeRole request, or when working with AWS resources that specify this value such as Lambda. Only valid when using the MONGODB-AWS authentication machinery. You must have an AWS admission key ID and a secret access key as well. Encounter Connect to an Atlas Cluster for example usage.

gssapiServiceName

Set the Kerberos service name when connecting to Kerberized MongoDB instances. This value must match the service name set on MongoDB instances to which you are connecting.

gssapiServiceName defaults to mongodb for all clients and MongoDB instances. If you change saslServiceName setting on a MongoDB example, you must set gssapiServiceName to match that setting.

gssapiServiceName is a deprecated aliases for authMechanismProperties=SERVICE_NAME:mongodb. For more information on which options your commuter supports and their relative priority to each other, reference the documentation for your preferred driver version.

MongoDB provides the following options to configure how MongoDB drivers and mongos instances select a server to which to straight read or write operations.

Connectedness Option

Description

localThresholdMS

The size (in milliseconds) of the latency window for selecting amid multiple suitable MongoDB instances. Default: fifteen milliseconds.

All drivers utilise localThresholdMS. Use the localThreshold allonym when specifying the latency window size to mongos.

serverSelectionTimeoutMS

Specifies how long (in milliseconds) to block for server selection earlier throwing an exception. Default: 30,000 milliseconds.

serverSelectionTryOnce

Unmarried-threaded drivers just. When truthful, instructs the commuter to scan the MongoDB deployment exactly once after server selection fails so either select a server or raise an error. When faux, the commuter blocks and searches for a server up to the serverSelectionTimeoutMS value. Default: true.

Multi-threaded drivers and mongos practise not back up serverSelectionTryOnce.

heartbeatFrequencyMS

heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the finish of the previous check until the beginning of the next one.

Default:

  • Unmarried-threaded drivers: threescore seconds.
  • Multi-threaded drivers: ten seconds.

mongos does non support changing the frequency of the heartbeat checks.

Connexion Option

Clarification

appName

Specify a custom app name. The app proper noun appears in

  • mongod and mongos logs,
  • the currentOp.appName field in the currentOp command and db.currentOp() method output,
  • the system.profile.appName field in the database profiler output.

The appName connectedness option is only applicable when provided to a MongoDB Driver. This parameter has no result when supplied to a client application such as MongoDB Compass or mongosh.

New in version 4.0.

retryReads

Enables retryable reads.

Possible values are:

  • true. Enables retryable reads for the connection.

    Official MongoDB drivers uniform with MongoDB Server 4.2 and later default to true.

  • faux. Disables retryable reads for the connection.

mongosh does not support retryable reads.

New in version four.2.

retryWrites

Enable retryable writes.

Possible values are:

  • true. Enables retryable writes for the connectedness.

    Official MongoDB 4.ii+ compatible drivers default to true.

  • faux. Disables retryable writes for the connectedness.

    Official MongoDB 4.0 and 3.6-compatible drivers default to imitation.

MongoDB drivers retry transaction commit and abort operations regardless of the value of retryWrites. For more data on transaction retryability, meet Transaction Error Treatment.

New in version 3.six.

uuidRepresentation

Possible values are:

standard
The standard binary representation.
csharpLegacy
The default representation for the C# driver.
javaLegacy
The default representation for the Java driver.
pythonLegacy
The default representation for the Python driver.

For the default, see the Drivers documentation for your commuter.

Note

Not all drivers support the uuidRepresentation option. For information on your driver, see the drivers documentation.

The following provide example URI strings for common connection targets.

The following connects to a database server running locally on the default port:

The following connects and logs in to the admin database every bit user sysop with the password moon:

                                      

mongodb://sysop:moon@localhost

The following connects and logs in to the records database equally user sysop with the password moon:

                                      

mongodb://sysop:moon@localhost/records

Use a URL encoded connection cord when connecting to a UNIX domain socket.

The post-obit connects to a UNIX domain socket with file path /tmp/mongodb-27017.sock:

                                      

mongodb://%2Ftmp%2Fmongodb-27017.sock

Non all drivers support UNIX domain sockets. For information on your driver, run into the Drivers documentation.

The following connects to a replica gear up with two members, one on db1.instance.net and the other on db2.example.cyberspace:

For a replica set, specify the hostname(s) of the mongod case(s) as listed in the replica set configuration.

                                      

mongodb://db1.example.net,db2.example.com/?replicaSet=exam

The following connects to a replica fix with three members running on localhost on ports 27017, 27018, and 27019:

For a replica set, specify the hostname(s) of the mongod instance(south) equally listed in the replica set configuration.

                                      

mongodb://localhost,localhost:27018,localhost:27019/?replicaSet=examination

The post-obit connects to a replica ready with three members and distributes reads to the secondaries:

For a replica gear up, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.

                                      

mongodb://example1.com,example2.com,example3.com/?replicaSet=exam&readPreference=secondary

The following connects to a replica set with write concern configured to wait for replication to succeed across a majority of the data-bearing voting members, with a two-second timeout.

For a replica set, specify the hostname(due south) of the mongod example(south) equally listed in the replica set configuration.

                                      

mongodb://example1.com,example2.com,example3.com/?replicaSet=test&w=majority&wtimeoutMS=2000

The following connects to a sharded cluster with three mongos instances:

                                      

mongodb://router1.example.com:27017,router2.example2.com:27017,router3.example3.com:27017/

New in version 4.4.

The post-obit connects to a MongoDB Atlas cluster which has been configured to back up authentication via AWS IAM credentials:

                                      

mongosh 'mongodb+srv://<aws access key id>:<aws hugger-mugger access central>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS'

Connecting to Atlas using AWS IAM credentials in this style uses the MONGODB-AWS authentication mechanism and the $external authSource, as shown in this example.

If using an AWS session token, as well, provide it with the AWS_SESSION_TOKEN authMechanismProperties value, as follows:

                                      

mongosh 'mongodb+srv://<aws access key id>:<aws hush-hush access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<aws session token>'

If the AWS admission key ID, the hugger-mugger admission fundamental, or the session token include the following characters:

those characters must be converted using per centum encoding.

Y'all may also gear up these credentials on your platform using standard AWS IAM environment variables. mongosh checks for the following surround variables when you utilise the MONGODB-AWS authentication mechanism:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_SESSION_TOKEN

If prepare, these credentials do non demand to be specified in the connection cord.

The post-obit example sets these environment variables in the bash trounce:

                                      
export AWS_ACCESS_KEY_ID='<aws access central id>'
consign AWS_SECRET_ACCESS_KEY='<aws secret admission primal>'
export AWS_SESSION_TOKEN='<aws session token>'

Syntax for setting environment variables in other shells will exist different. Consult the documentation for your platform for more information.

Yous can verify that these environment variables have been gear up with the post-obit control:

Once gear up, the following case connects to a MongoDB Atlas cluster using these environment variables:

                                      

mongosh 'mongodb+srv://cluster0.case.com/testdb?authSource=$external&authMechanism=MONGODB-AWS'

demarcolawen1989.blogspot.com

Source: https://docs.mongodb.com/manual/reference/connection-string/

0 Response to "How to Read if (Std::cin >> )"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel