Connect to MongoDB

Deployment Type:
Client:

    Author: MongoDB Documentation Team

    There are several ways to connect to your MongoDB instance.

    The following guide steps you through installing the MongoDB client of your choice.

    Time required: 15 minutes

    What You’ll Need

    If you are using MongoDB in the Cloud (Atlas), you will need to:

    Or, if you plan on using a local instance of MongoDB, you will need to:

    Check Your Environment

    • Ensure that your client platform is compatible with MongoDB. Refer to the Supported Platforms table for more information.

    Procedure

    Tip

    Select the client and environment you will use at the top of this page.

    1

    Install your client

    The mongo shell is packaged with the MongoDB Server Community and Enterprise distributions, and is also available for users of Atlas as a client-only download.

    MongoDB binaries are located in a directory that starts with “mongodb-“. You should see a file named mongo, which is the shell executable.

    If you do not have mongo shell installed, follow the install directions for your environment.

    If you do not already have a mongo shell, you can download just the shell by logging into Atlas. For your cluster, click Connect.

    ../../_images/connect_panel.png

    Under Check the IP Whitelist, add the IP address of the client you wish to have connecting to Atlas. Then click the Connect with the Mongo Shell. Follow the instructions in the dialog to download and install the shell.

    ../../_images/whitelistpanel.png

    Download the latest stable version for your environment.

    After downloading, click on the downloaded .msi file. The Windows Installer will guide you through the installation.

    Download the latest stable version for your environment.

    Double click the tgz file to untar the file.

    Download the latest stable version for your environment.

    Extract the tar file and locate the mongo executable under the bin directory of your install root.

    tar -xvzf <tgz file>
    

    To install Compass, see the Compass installation instructions

    To install Pymongo, see the Pymongo documentation.

    To install the Java driver, see the Java Driver documentation

    To install the node.js driver, see the Node.js Driver documentation

    To install Motor, see the Motor documentation

    To install the C#/.NET driver, see the C# Driver documentation

    The MongoDB Go driver can be installed using go get:

    go get github.com/mongodb/mongo-go-driver
    

    The output of this may look like a warning stating something like:

    package github.com/mongodb/mongo-go-driver: no Go files in (...).
    

    This is expected output.

    Alternatively if you are using the dep package manager to install the driver, you can install the main mongo package as well as the bson and mongo/options package using this command:

    dep ensure --add github.com/mongodb/mongo-go-driver/mongo \
    github.com/mongodb/mongo-go-driver/bson \
    github.com/mongodb/mongo-go-driver/mongo/options
    
    2

    Obtain your MongoDB connection string

    Tip

    If you are using Compass, skip this step.

    In order to connect to MongoDB, you will need a URI string. A URI (Uniform Resource Identifier) is similar to a URL, and is supplied as a parameter to the mongo shell, Compass, and the MongoDB drivers when connecting to a MongoDB deployment.

    Note

    You can create a URI string for your session in MongoDB Guides by copying and pasting your Atlas connection string in the form below. Once you copy the string here, any relevant code examples within the MongoDB Guides will be populated with a URI string. If you have not already retrieved your Atlas connection string, see Set Up Atlas Connectivity guide.

    The URI string used in the guides assumes you have set up authentication for your MongoDB instance, and have created a username and password for read and write access to a MongoDB database.

    If you have already set up a user with the readWriteAnyDatabase role through the Secure your MongoDB Deployment guide, you may use that username and password here, along with the admin database in your connection string.

    Note

    The URI form below allows you to create a URI string for your session in MongoDB Guides by filling out a form. Once you fill out the form, any relevant code examples within the MongoDB Guides will be populated with a URI string. You can change these at any time by repopulating the form.

    Important

    If your connection string contains $[password], you will need to replace this string with your password. Use caution where you store and enter passwords, particularly when running from a shell or command prompt. Special characters in passwords must be escaped.

    Server deployment type
    • local MongoDB
    • local MongoDB with replica set
    Servers
    3

    Connect to your MongoDB instance

    Tip

    Have you whitelisted your IP address for access to Atlas? For more details see Step 3, Whitelist your IP Address and Select Your Connection Method in Set Up Atlas Connectivity.

    Select the operating system platform on which you are running the MongoDB client you have selected.

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo.exe <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    If you wish to manually configure your Compass connection, load Compass and select the New Connection link. You will see a form where you can enter connection information for MongoDB.

    Atlas users can copy a URI string from the Atlas console into Compass. MongoDB Compass can detect whether you have a MongoDB URI connection string in your system clipboard and auto- populate the connection dialog from the URI.

    See Set Up Atlas Connectivity for information on how to get the Atlas connection string URI into your copy buffer.

    If Compass was already running when you copied the URI string, click the NEW CONNECTION button.

    ../../_images/connect-to-host.png

    You will be prompted to populate the connection dialog. Click Yes.

    You should then populate the password field with the proper password for your MongoDB user in the connection form.

    Note

    Errors related to connecting through Compass will appear in red at the top of the Connect screen.

    It’s a good idea to put your connection code in a class so that it can be reused.

    from pymongo import MongoClient
    
    class Connect(object):
        @staticmethod    
        def get_connection():
            return MongoClient("<URISTRING>")
    

    If your connection_string starts with mongodb+srv, you need to install the dnspython module with

    python -m pip install dnspython
    

    Now add code to call the class you just created.

    from connect import Connect
    from pymongo import MongoClient
    
    connection = Connect.get_connection()
    

    For the MongoDB java driver 3.7 and beyond, use the MongoClients.create() method.

        final String uriString = "<URISTRING>";
        MongoClient mongoClient = MongoClients.create(uriString);
    

    For legacy drivers (prior to 3.7), use:

        final String uriString = "<URISTRING>";
        MongoClientURI uri = new MongoClientURI(uriString);
        MongoClient mongoClient = new MongoClient(uri);
    
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    
    // Connection URL
    const url = '<URISTRING>';
    
    // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, client) {
      assert.equal(null, err);
      client.close();
    });
    

    The MongoDB.Bson package is used in CRUD operations, so you’ll import it here.

    using System;
    using MongoDB.Bson;
    using MongoDB.Driver;
    
    namespace csharptest
    {
        class Connect
        {
            static void Main(string[] args)
            {
               var client = new MongoClient("<URISTRING>");
            }
        }
    }
    

    Replace your password and any parameters surrounded by $[] in the connection string in the code below.

    For now, you will use the context.TODO().

    Later you’ll configure the context specific to your requirements.

    client, err := mongo.Connect(context.TODO(), "<URISTRING>");
    
    if err != nil {
    	log.Fatal(err)
    }
    

    You won’t know if the connection has been successful until you use the connection. A ping is one way you can test the connection. This is a full example of a Go connection to mongoDB, including a test ping.

    package main
    
    import (
    	"context"
    	"fmt"
    	"github.com/mongodb/mongo-go-driver/mongo"
    	"log"
    )
    
    func main() {
    	// Open Connection
    	client, err := mongo.Connect(context.TODO(), "<URISTRING>");
    
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// End Open Connection Code
    
    	// Check the connection
    	err = client.Ping(context.TODO(), nil)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Println("Connected to MongoDB!")
    
    }
    

    In your Go workspace and project folder, run build.

    go build
    

    Now run the binary. For binaries that are not installed, you’ll have to specify the path.

    go <path-to-yourproject>
    

    If you’d like to run the resulting binary without specifying a path, install the binary you just built into your Go workspace.

    go install
    

    Now run the code. “yourprojectname” is the name of the project directory that contains the file with your main() function.

    For installed binaries use:

    go yourprojectname
    

    For binaries that are not installed, you’ll have to specify the path.

    go ./yourprojectname
    

    The default timeout for the Go driver to connect to the database is 30 seconds. In the event that you are unable to connect, you will see an error that resembles this:

    2019/01/09 10:01:50 server selection timeout
    

    Summary

    Congratulations. If you have successfully completed this guide, you have connected to your MongoDB instance. In the next group of guides, you’ll learn how to create, read, update, and delete data in MongoDB.

    What’s Next

    In the next guide, you’ll learn how to insert data into MongoDB.