Navigation

Connection Guide

This guide shows you how to connect to a MongoDB instance or replica set deployment using the Node.js driver.

The connection URI is the set of instructions that the driver uses to connect to a MongoDB deployment. It instructs the driver on how it should connect to MongoDB and how it should behave while connected. The following example shows each part of the connection URI:

Each part of the connection string

In this example, for the protocol, we use mongodb+srv which specifies the DNS Seedlist Connection Format. This indicates that the hostname following it corresponds to the DNS SRV record of your MongoDB instance or deployment. If your instance or deployment does not have a DNS SRV record, use mongodb to specify the Standard Connection Format.

Note

If your deployment is on MongoDB Atlas, follow the Atlas driver connection guide to retrieve your connection string.

The next part of the connection string contains your username and password if you are using password-based authentication. Replace the value of user with your username and pass with your password. If you are using an authentication mechanism that does not require a username and password, omit this part of the connection URI.

The next part of the connection string specifies the hostname or IP address and port of your MongoDB instance. In the example above, we use sample-hostname as the hostname and 27017 as the port. Replace these values to point to your MongoDB instance.

The last part of the connection string contains connection and authentication options as parameters. In the example above, we set two connection options: poolSize=20 and writeConcern=majority. For more information on connection options, skip to the Connection Options section.

The code below shows how you can use the sample connection URI in a client to connect to MongoDB.

const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"mongodb+srv://sample-hostname:27017/?poolSize=20&writeConcern=majority";
// Create a new MongoClient
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);

A MongoDB replica set deployment is a group of connected instances that store the same set of data. This configuration of instances provides data redundancy and high data availability.

To connect to a replica set deployment, specify the hostname and port numbers of each instance, separated by a comma, and the replica set name as the value of the replicaSet parameter in the connection string.

mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRs
Note

Although it is possible to connect to a replica set deployment by providing only a single host, you should provide the driver with the full list to ensure that it is able to connect even if one host fails.

This section explains several common MongoDB connection and authentication options. You can pass the connection options as parameters of the connection URI to specify the behavior of the client.

Option Name
Type
Default Value
Description
connectTimeoutMS
integer
10000
Specifies the number of milliseconds to wait before timeout on a TCP connection.
family
number
null
Specifies the version of the Internet Protocol (IP). The valid values are: 4, 6, 0, or null. The 0 and null settings attempt to connect with IPv6 and fall back to IPv4 upon failure.
forceServerObjectId
boolean
false
Specifies whether to force the server to assign _id values to documents instead of the driver.
ignoreUndefined
boolean
false
Specifies whether the BSON serializer should ignore undefined fields.
keepAlive
boolean
true
Specifies whether to enable keepAlive on the TCP socket. For more information, see the documentation for Node.js socket.setKeepAlive.
keepAliveInitialDelay
integer
30000
Specifies the number of milliseconds to wait before initiating keepAlive on the TCP socket. For more information, see the documentation for Node.js socket.setKeepAlive.
logger
object
null
Specifies a custom logger for the client to use.
loggerLevel
string
null
Specifies the logger level used by the driver. Valid choices are: error, warn, info, and debug.
maxPoolSize
integer
10
You must set the useUnifiedTopology option to true to use this option. Specifies the maximum number of connections that a connection pool may have at a given time.
maxIdleTimeMS
integer
You must set the useUnifiedTopology option to true to use this option. Specifies the maximum amount of time a connection can remain idle in the connection pool before being removed and closed.
minSize
integer
0
Specifies the minimum size of the instance connection pool.
minPoolSize
integer
0
You must set the useUnifiedTopology option to true to use this option. Specifies the minimum number of connections that must exist at any moment in a single connection pool.
noDelay
boolean
true
Specifies whether to use the TCP socket no-delay option. For more information, see the documentation for Node.js socket.setNoDelay.
pkFactory
object
null
Specifies a primary key factory object that generates custom _id keys.
poolSize
integer
5
Specifies the maximum size of the instance connection pool.
promiseLibrary
object
null
Specifies the Promise library class the application uses (e.g. Bluebird). This library must be compatible with ES6.
promoteBuffers
boolean
false
Specifies whether to promote Binary BSON values to native Node.js Buffer type data.
promoteLongs
boolean
true
Specifies whether to convert Long values to a number if they fit inside 53 bits of resolution.
promoteValues
boolean
true
Specifies whether to promote BSON values to Node.js native types when possible. When set to false, it uses wrapper types to present BSON values.
raw
boolean
false
Specifies whether to return document results as raw BSON buffers.
serializeFunctions
boolean
false
Specifies whether to serialize functions on any object passed to the server.
socketTimeoutMS
integer
360000
Specifies the number of milliseconds to wait before timeout on a TCP socket.
tls
boolean
false
Specifies whether to establish a Transport Layer Security (TLS) connection with the instance. This is automatically set to true when using a DNS seedlist (SRV) in the connection string. You can override this behavior by setting the value to false.
useUnifiedTopology
boolean
true
Specifies whether to use the unified topology layer. To learn what the unified topology layer is and why it was introduced, see this document.
validateOptions
boolean
false
Specifies whether to error when the method parameters contain an unknown or incorrect option. If false, the driver produces warnings only.
waitQueueTimeoutMS
integer
0
You must set the useUnifiedTopology option to true to use this option. Specifies the maximum amount of time in milliseconds that operation execution can wait for a connection to become available.
writeConcern
string or integer
null
Specifies the write concern. For more information on values, see the server documentation on the w Option.

For a complete list of options, see the MongoClient API reference page.

Give Feedback