Docs Menu

Connection Guide

On this page

  • Connection URI
  • Other Ways to Connect to MongoDB
  • Connect to a MongoDB Server on Your Local Machine
  • Connect to a Replica Set
  • Direct Connection
  • Connection Options

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: maxPoolSize=20 and w=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/?maxPoolSize=20&w=majority";
// Create a new MongoClient
const client = new MongoClient(uri);
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);

If you are connecting to a single MongoDB server instance or replica set that is not hosted on Atlas, see the following sections to find out how to connect.

If you need to run a MongoDB server on your local machine for development purposes instead of using an Atlas cluster, you need to complete the following:

  1. Download the Community or Enterprise version of MongoDB Server.
  2. Install and configure MongoDB Server.
  3. Start the server.
Important

Always secure your MongoDB server from malicious attacks. See our Security Checklist for a list of security recommendations.

After you successfully start your MongoDB server, specify your connection string in your driver connection code.

If your MongoDB Server is running locally, you can use the connection string "mongodb://localhost:<port>" where <port> is the port number you configured your server to listen for incoming connections.

If you need to specify a different hostname or IP address, see our Server Manual entry on Connection Strings.

To test whether you can connect to your server, replace the connection string in the Connect to MongoDB Atlas code example and run it.

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

When making a connection, the driver takes the following actions by default:

  • Discovers all replica set members when given the address of any one member.
  • Dispatches operations to the appropriate member, such as write against the primary.
Tip

You only need to specify one host to connect to a replica set. However, to ensure connectivity if the specified host is unavailable, provide the full list of hosts.

To force your operations to run on the host specified in your connection URI, you can specify the directConnection connection option. If you specify this option, you must use the standard connection URI format. The driver does not accept the DNS seedlist connection format (SRV) when you specify this option.

When you specify directConnection and connect to a secondary member of the replica set, your write operations fail because it is not the primary member. To perform read operations, you must enable secondary reads. See the read preference options for more information.

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
120000
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
100
Specifies the maximum number of connections that a connection pool may have at a given time.
maxIdleTimeMS
integer
Specifies the maximum amount of time a connection can remain idle in the connection pool before being removed and closed.
minPoolSize
integer
0
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.
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.
serverApi
string or enum
null
Specifies the API version that operations must conform to. See the MongoDB manual entry on Versioned API for more information.
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.
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
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.
directConnection
boolean
false
Specifies whether to force dispatch all operations to the host specified in the connection URI.

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

Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.