Navigation

    Quick Start

    This guide shows you how to create an application that uses the Node.js driver to connect to a MongoDB Atlas cluster. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers.

    The Node.js driver is an interface through which you can connect to and communicate with MongoDB instances.

    MongoDB Atlas is a fully-managed cloud database service that hosts your data on MongoDB instances. We show you how to get started with your own free (no credit card required) instance in this guide.

    Follow the steps below to connect your Node.js application with a MongoDB instance.

    Set up Your Project

    Install Node and NPM

    Ensure your system has Node.js version 10 or later and a compatible version of NPM (Node Package Manager) installed. For more information on how to check your version of Node and NPM and installation instructions for your system, see downloading and installing Node.js and npm.

    Initialize the Project

    After you verify that you installed the required versions of Node and NPM, create a new project.

    First, create a directory for your project in your command line interface:

    mkdir node_quickstart

    Then, navigate into that directory so you can work directly with your project's files:

    cd node_quickstart

    Next, set up NPM for your project by running the following command. This command creates a file called package.json:

    npm init -y

    Why the -y?

    If you specify the -y option in the command, NPM automatically accepts the default values for the command. Omit the -y flag to interactively select your project settings.

    Add MongoDB as a Dependency

    Next, add the official Node.js MongoDB driver to your project dependencies. Use the following command to instruct NPM to download and install the mongodb package.

    npm install mongodb

    This command downloads mongodb package and dependencies required for its installation and saves them into a directory called node_modules in your project directory, and records the dependency information in the package.json file you generated in the previous step.

    At this point, you should have appropriate versions of Node.js and NPM installed as well as a project directory that contains the dependencies you need to use the Node.js MongoDB driver.

    Create a MongoDB Cluster

    Set up a Free Tier Cluster in Atlas

    After installing the Node MongoDB driver, create a MongoDB instance to store and manage your data. Complete the Get Started with Atlas guide to set up a new Atlas account, free tier cluster (MongoDB instance), load datasets, and interact with the data.

    After completing the steps in the Atlas guide, you should have a new MongoDB cluster deployed in Atlas, a new database user, and sample datasets loaded into your cluster.

    Connect to your Cluster

    In this step, we create and run an application that uses the Node.js MongoDB driver to connect to your instance of MongoDB and run a query on the sample data.

    We pass instructions to the driver on where and how to connect to your MongoDB instance in a string called the connection string. This string includes information on the hostname or IP address and port of your instance, authentication mechanism, user credentials when applicable, and other connection options.

    To retrieve your connection string for the instance and user you created in the previous step, log into your Atlas account and navigate to the Clusters section and click the Connect button for the cluster that you want to connect to as shown below.

    /includes/figures/atlas_connection_select_cluster.png

    Proceed to the Connect Your Application step and select the Node.js driver. Select the "Connection String Only" tab and click the Copy button to copy the connection string to your clipboard as shown below.

    /includes/figures/atlas_connection_copy_string.png

    Save your connection string to a safe location that you can access in the next step.

    Next, create a file to contain your application called index.js in your node_quickstart directory. Add the following code, replacing the uri variable with your connection string. Make sure to replace the "<password>" section of the connection string with the password you created for your user that has atlasAdmin permissions.

    const { MongoClient } = require("mongodb");
    
    // Replace the uri string with your MongoDB deployment's connection string.
    const uri =
      "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority";
    
    const client = new MongoClient(uri);
    
    async function run() {
      try {
        await client.connect();
    
        const database = client.db('sample_mflix');
        const collection = database.collection('movies');
    
        // Query for a movie that has the title 'Back to the Future'
        const query = { title: 'Back to the Future' };
        const movie = await collection.findOne(query);
    
        console.log(movie);
      } finally {
        // Ensures that the client will close when you finish/error
        await client.close();
      }
    }
    run().catch(console.dir);

    Run the sample code with the following command from your command line:

    node index.js

    When you run the command, the sample code should output the details of the movie which resembles the following:

    {
      _id: ...,
      plot: 'A young man is accidentally sent 30 years into the past...',
      genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
      ...
      title: 'Back to the Future',
      ...
    }

    If or receive an error, check whether you included the proper connection string in the application code, and loaded the sample dataset in your Atlas cluster.

    After completing this step, you should have a working application that uses the Node.js driver to connect to your MongoDB instance, run a query on the sample data, and prints out the result.

    Next Steps

    Learn how to read and modify data using the Node.js driver in our CRUD Operations guide or how to perform common operations in our usage examples.