MongoDB connection string

MongoDB connection string | Complete tutorial in [2022]

This tutorial will explore the different ways to connect to MongoDB via connection string. We will explore the MongoDB connection string for standalone setup, replica set, and TLS enabled mongodb. We will also explore the MongoDB connection string for different drivers like python, C+, JAVA, and Nodejs.

MongoDB connection string example

MongoDB connection string example

There are numerous ways using which a person can install MongoDB. You can install MongoDB to run locally or on a single VM or in a cluster of VM’s. This session will explain various methods to connect to the mongodb instance.

MongoDB connection string localhost

Localhost deployment is preferred for development and testing purposes only.MongoDB localhost deployment is not at all recommended for production deployment.

To connect to mongodb in localhost, you need to type the below command

mongodb://localhost:27017

MongoDB connection string standalone

Mongodb standalone deployment is preferred when deploying the MongoDB for some POC or in a test/development environment. For Production, theStandalone deployment of MongoDB is not preferred because it leads to a single point of failure.

For a standalone deployment of mongodb, type the below command to connect to the mongodb instance

mongodb://<mongodb0.example.com>:27017

whereas:

  • mongodb:// = A required prefix to identify that this is a string in the standard connection format
  • host[:port] = The host and port where the mongo instance is running.

MongoDB connection string for replica set

In MongoDB replica set deployment, we deployed mongodb over multiple servers for high availability, fault tolerance, and high performance

For a replica set, theMongoDB connection string is

mongodb://mongodb1.example.com:27017,mongodb2.example.com:27017,mongodb3.example.com:27017/?replicaSet=<myRepl>

where:

  • mongodb:// = A required prefix
  • mongodb1.example.com:27017,mongodb2.example.com:27017,mongodb3.example.com:27017 = List of servers and port where MongoDB is installed. The list of servers and ports should be comma separated
  • replicaSet=<myRepl> = Name of the replicaSet which is setup during mongodb deploying

MongoDB connection string with username and password

If you have setup mongodb to authenticate the user via credentials, then type the below command to connect to mongodb

mongodb://[username:[email protected]]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database.collection][?options]]

where:

  • mongodb:// = A required prefix
  • username:[email protected] = mongodb usename and password followed by “@”
  • host1[:port1][,host2[:port2],…[,hostN[:portN]]] = mongodb host and port where mongodb is installed
  • database.collection = the database and connection you want to connect
  • ?options = Any additional options.Note that even if the database is absent there is still a / required between the last host and the ? introducing the options.

MongoDB connection string with database name

If you want to connect to any particular database of mongodb via username and password, then you need to use the below connection string

mongodb://<user>:<pwd>@host1[:port1][,host2[:port2],…[,hostN[:portN]]]/<dbName>?options

where

  • mongodb:// = A required prefix
  • <user>:<pswd>@ = mongodb username and password followed by “@”
  • host1[:port1][,host2[:port2],…[,hostN[:portN]]] = mongodb host and port where mongodb is installed
  • <dbName> = the mongodb database you want to connect to
  • ?options = Any additional options.

For example, type the below command to connect to mongodb where

  • user= naiveskill
  • password=test
  • mongo server = testmon101,testmon102,testmon103
  • mongo port = 27017
  • database to connect to = naive
  • replicaset = foo
mongodb://naiveskill:[email protected]testmon101:27017,testmon102:27017,testmon103:27017/naive?replicaSet=foo
MongoDB connection string C#

MongoDB connection string C#

MongoDB provides support for many languages using which users can interact with mongodb, and one such language is C#.

You need to install the required libraries to get started with C# on the mongodb client. Follow this link to install the mongodb c# library.

After successful installation, you can use the below code snippet to connect to mongodb via c#

using MongoDB.Bson;
using MongoDB.Driver;
var client = new MongoClient(
    "mongodb+srv://<user>:<pswd>@<cluster-address>/<database>?options"
);

where

  • mongodb+srv:// = A required prefix to connect to. mongodb
  • <user>:<pswd>@ = Mongodb username:password followed by “@”
  • cluster-address is the Mongodb server name where MongoDB is installed.It usually follows host1[:port1][,host2[:port2],…[,hostN[:portN]]] syntex
  • <database> = the mongodb database you want to connect to
  • ?options = Any additional options.

More information about the MongoDB C# driver can be found here

MongoDB connection string Java

With Mongodb java driver, we can interact with mongodb via java language. We need to install the required libraries before working on the java driver.

Refer to the command below to connect to theMongoDB connection string via Java.

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;
import com.mongodb.MongoCredential;
import com.mongodb.MongoClientOptions;
import java.util.Arrays;
MongoClient mongoClient = new MongoClient(
    new MongoClientURI("mongodb://host1:27017,host2:27017,host3:27017"));

If you wish to connect to a replica set, you can use the following connection string.

MongoClient mongoClient = new MongoClient(
    new MongoClientURI(
      "mongodb://<host1>:<port>,<host2>:<port>,<host3>:<port>/?replicaSet=<myReplicaSet>"));

MongoDB connection string Python

Python is a very popular language and is the first choice for most data scientists regarding language selection. Mongodb also provides a driver to connect to mongodb via python. The driver’s name is pymongo.

Follow the MongoDB with python tutorial to understand how to work with the pymongo driver.

You can use the below code snippet to connect to mongodb via python.

import pymongo
client = pymongo.MongoClient("mongodb://<host1>:<port>,<host2>:<port>,<host3>:<port>/?replicaSet=<myReplicaSet>")

MongoDB connection string Nodejs

The official MongoDB Node.js driver allows your Node.js applications to connect to MongoDB.The driver features an asynchronous API that will enable you to access method return values through Promises or specify callbacks to access them when communicating with MongoDB.

To work with theNodejs driver, you need to install the required libraries. Now, use the below code snippet to connect to the mongo client.

const { MongoClient } = require("mongodb");
const uri =mongodb://<host1>:<port>,<host2>:<port>,<host3>:<port>/?options
const client = new MongoClient(uri);

TLS enabled mongodb connection string

TLS/SSL is the best way to secure the data in motion. If you set up the Mongodb with tls/SSL then, you can use the snippet below to connect to MongoDB.

Connect to Mongodb over TLS/SSL without Client Certificate Validation

You can type the below command to connect to MongoDB, whose certificate is signed using a Root Ca

mongodb://<user>:<password>@<server>:<port>/<database>?ssl=true

Connect to Mongodb over TLS/SSL with Client Certificate Validation

If the admin/developer setup the MongoDB to authenticate the client certificate, then we need to pass the certificate path while connecting to the mongo instance.

Type the below command to connect to MongoDB over TLS/SSL with Client Certificate Validation

mongodb://<user>:<[email protected]><server:port>?ssl=true&sslclientcertificatekeyfile=/<path_of_certificate file>/client.pem

Conclusion

I hope you liked this tutorial. This blog has explored mongodb connection strings based on the mongodb deployments. We have also seen the mongodb connection string for C#, JAVA, python, and Nodejs. Please let me know if you need further details regarding mongodb connection strings.

More to explore?

How to create a database in mongodb

Install MongoDB using docker

Mongodb insert command

MongoDB vs Mysql

Mongodb vs PostgreSQL

Mongodb vs dynamodb

Leave a Comment

Your email address will not be published.

Scroll to Top