Getting Started With MongoDB As A Docker Container Deployment

Getting Started With MongoDB As A Docker Container Deployment

In this tutorial we’re going to focus on using Docker to deploy MongoDB as a container and interact with it with the shell client.

In this tutorial we’re going to focus on using Docker to deploy MongoDB as a container and interact with it with the shell client.

MongoDB is one of the most popular NoSQL databases on the market right now and is used heavily with Node.js development in particular. So what if you wanted to give MongoDB a spin and see what it’s all about?

There are plenty of deployment options when it comes to using MongoDB. For example, I had recently written a tutorial titled, Developing a RESTful API with Node.js and MongoDB Atlas which focused on the MongoDB cloud solution called Atlas. However, you can also install MongoDB on premise using multiple options.

Downloading the Latest MongoDB Docker Image

Assuming that you have Docker installed on your computer or server, we can obtain the MongoDB image from the Docker Hub container registry. There are numerous images available, each representing different versions of MongoDB or the underlying operating system that it is installed on.

The simplest solution to download our image is to execute the following:

docker pull mongo

The above command will get the latest tag which could be anything. This is great if you want to be bleeding edge, but when you’re doing realistic deployments you probably want to be in control of the versioning information. Instead, you might want to specify the tag like this:

docker pull mongo:4.0.4

At the time of writing this, MongoDB 4.0.4 is the latest version and it is what the latest tag represents. This time we’re actually specifying the 4.0.4 tag because that is what we want.

It may take a moment, but when it is done, we have an image that is ready for deployment.

Deploying an Instance of MongoDB as a Container

With the image available to us, we need to deploy it. In its simplest form, and what is outlined in the Docker Hub documentation, we can execute the following command:

docker run --name mongodb mongo:4.0.4

This command works, but there are potentially a few problems. What we’re doing is we are running a container and naming it mongodb. We aren’t running it in the background and if we wanted to connect to it, we’d have to do it from another container instance. In other words, we wouldn’t be able to connect to it from our host computer or server.

Instead, what we could do is the following:

docker run -d -p 27017-27019:27019 --name mongodb mongo:4.0.4

The above command will run the container in detached mode, or in the background for us. We are also mapping the container ports with host ports so that way we can access the database from a host level application if we wanted to. The ports used were taken from the MongoDB documentation. You don’t need to map the ports in order to use MongoDB. Like I said, the port mapping is only necessary if you wish to use it from your host Mac, Windows, or Linux computer. If you plan to deploy all your applications as micro-services with Docker, then you’d be fine as long as your containers can communicate with each other.

Interacting with the MongoDB Docker Container with Basic Shell Operations

At this point in time we have a functional MongoDB deployment. Rather than creating an application to make use of it, we’re going to interact with the database through the shell client.

If you’ve been following along so far, your container is currently running in detached mode. This means that we need to connect to it using the interactive terminal:

docker exec -it mongodb bash

The above command will connect to our deployment named mongodb using the interactive terminal and start the bash shell. More details on connecting to detached Docker containers can be found in my previous tutorial titled, Connecting to a Detached Docker Container for Terminal Interaction.

You’ll notice that you are now using your Terminal as if you were inside your container. This is where we can start using MongoDB.

To launch the MongoDB shell client, execute the following:

mongo

When inside the MongoDB shell client, you can access all the functionality that is outlined in the MongoDB documentation. For example, we can see what databases exist in our instance with the following:

show dbs

To create a new database, we can use a multi-step process, the first being to define the database we wish to use:

use thepolyglotdeveloper

We’re using the database thepolyglotdeveloper, but it doesn’t exist until we start creating collections and data. To create a collection with data, we can do something like this:

db.people.save({ firstname: "Nic", lastname: "Raboy" }) db.people.save({ firstname: "Maria", lastname: "Raboy" })

With two documents created in a new people collection in our thepolyglotdeveloper database, we can query for data using something like the following:

db.people.find({ firstname: "Nic" })

There is a lot that you can accomplish with the shell client, but you can get the general idea. What we did prove is that we were able to interact with the container instance.

Conclusion

You just saw how to download and deploy a Docker image of MongoDB as a container, then interact with it using the shell client. Docker isn’t the only way to deploy MongoDB and the shell client isn’t the only way to interact with it. These are just two of many examples on what you can accomplish.

If you want to learn more about Docker, consider enrolling in my video course titled, Containerization with Docker by Example.

A video version of this article can be seen below.

How to connect to MongoDB database from Node.js?

How to connect to MongoDB database from Node.js?

Use Node.js? Want to learn MongoDB? In today’s post, we’ll work through connecting to a MongoDB database from a Node.js script, retrieving a list of databases, and printing the results to your console.

In today’s post, we’ll work through connecting to a MongoDB database from a Node.js script, retrieving a list of databases, and printing the results to your console.

Set up

Before we begin, we need to ensure you’ve completed a few prerequisite steps.

Install Node.js

First, make sure you have a supported version of Node.js installed (the MongoDB Node.js Driver requires Node 4.x or greater and for these examples, I've used Node.js 10.16.3).

Install the MongoDB Node.js Driver

The MongoDB Node.js Driver allows you to easily interact with MongoDB databases from within Node.js applications. You’ll need the driver in order to connect to your database and execute the queries described in this Quick Start series.

If you don’t have the MongoDB Node.js Driver installed, you can install it with the following command.

npm install mongodb

At the time of writing, this installed version 3.3.2 of the driver. Running npm list mongodb will display the currently installed driver version number. For more details on the driver and installation, see the official documentation.

Create a free MongoDB Atlas cluster and load the sample data

Next, you’ll need a MongoDB database. Your database will be stored inside of a cluster. At a high level, a cluster is a set of nodes where copies of your database will be stored.

The easiest way to get started with MongoDB is to use Atlas, MongoDB’s fully-managed database-as-a-service. Head over to Atlas and create a new cluster in the free tier. Once your tier is created, load the sample data.

Get started with an M0 cluster on Atlas today. It's free forever, and it’s the easiest way to try out the steps in this blog series.

If you’re not familiar with how to create a new cluster and load the sample data, check out this video tutorial from MongoDB Developer Advocate Maxime Beugnet.

Get your cluster’s connection info

The final step is to prep your cluster for connection.

In Atlas, navigate to your cluster and click CONNECT. The Cluster Connection Wizard will appear.

The Wizard will prompt you to whitelist your current IP address and create a MongoDB user if you haven’t already done so. Be sure to note the username and password you use for the new MongoDB user as you’ll need them in a later step.

Next, the Wizard will prompt you to choose a connection method. Select Connect Your Application. When the Wizard prompts you to select your driver version, select Node.js and 3.0 or later. Copy the provided connection string.

For more details on how to access the Connection Wizard and complete the steps described above, see the official documentation.

Connect to your database from a Node.js application

Now that everything is set up, it’s time to code! Let’s write a Node.js script that connects to your database and lists the databases in your cluster.

Import MongoClient

The MongoDB module exports MongoClient, and that’s what we’ll use to connect to a MongoDB database. We can use an instance of MongoClient to connect to a cluster, access the database in that cluster, and close the connection to that cluster.

const {MongoClient} = require('mongodb');

Create our main function

Let’s create an asynchronous function named main() where we will connect to our MongoDB cluster, call functions that query our database, and disconnect from our cluster.

The first thing we need to do inside of main() is create a constant for our connection URI. The connection URI is the connection string you copied in Atlas in the previous section. When you paste the connection string, don’t forget to update <username> and <password> to be the credentials for the user you created in the previous section. Note: the username and password you provide in the connection string are NOT the same as your Atlas credentials.

/**
 * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
 * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
 */
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";

Now that we have our URI, we can create an instance of MongoClient.

const client = new MongoClient(uri);

Note: When you run this code, you may see DeprecationWarnings around the URL string parser and the Server Discover and Monitoring engine. If you see these warnings, you can remove them by passing options to the MongoClient. For example, you could instantiate MongoClient by calling new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }). See the Node.js MongoDB Driver API documentation for more information on these options.

Now we’re ready to use MongoClient to connect to our cluster. client.connect() will return a promise. We will use the await keyword when we call client.connect() to indicate that we should block further execution until that operation has completed.

await client.connect();

Now we are ready to interact with our database. Let’s build a function that prints the names of the databases in this cluster. It’s often useful to contain this logic in well named functions in order to improve the readability of your codebase. Throughout this series, we’ll create new functions similar to the function we’re creating here as we learn how to write different types of queries. For now, let’s call a function named listDatabases().

await listDatabases(client);

Let’s wrap our calls to functions that interact with the database in a try/catch statement so that we handle any unexpected errors.

try {
    await client.connect();

    await listDatabases(client);

} catch (e) {
    console.error(e);
}

We want to be sure we close the connection to our cluster, so we’ll end our try/catch with a finally statement.

finally {
    await client.close();
}

Once we have our main() function written, we need to call it. Let’s send the errors to the console.

main().catch(console.err);

Putting it all together, our main() function and our call to it will look something like the following.

async function main(){
    /**
     * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
     * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
     */
    const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";

    const client = new MongoClient(uri);

    try {
        // Connect to the MongoDB cluster
        await client.connect();

        // Make the appropriate DB calls
        await  listDatabases(client);

    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.err);

List the databases in our cluster

In the previous section, we referenced the listDatabases() function. Let’s implement it!

This function will retrieve a list of databases in our cluster and print the results in the console.

async function listDatabases(client){
    databasesList = await client.db().admin().listDatabases();

    console.log("Databases:");
    databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};

Save Your File

You’ve been implementing a lot of code. Save your changes, and name your file something like connection.js. To see a copy of the complete file, visit the nodejs-quickstart GitHub repo.

Execute Your Node.js Script

Now you’re ready to test your code! Execute your script by running a command like the following in your terminal: node connection.js

You will see output like the following:

Databases:
 - sample_airbnb
 - sample_geospatial
 - sample_mflix
 - sample_supplies
 - sample_training
 - sample_weatherdata
 - admin
 - local

What’s next?

Today, you were able to connect to a MongoDB database from a Node.js script, retrieve a list of databases in your cluster, and view the results in your console. Nice!

In future posts in this series, we’ll dive into each of the CRUD (create, read, update, and delete) operations as well as topics like change streams, transactions, and the aggregation pipeline, so you’ll have the tools you need to successfully interact with data in your databases.

In the meantime, check out the following resources:

Series versions

This examples in this article were created with the following application versions:

MongoDB: 4.0
MongoDB Node.js Driver: 3.3.2
Node.js: 10.16.3

MongoDB Tutorial - How to backup and restore a database

MongoDB Tutorial - How to backup and restore a database

This is a quick example to show how to easily backup and restore a MongoDB database from the command line, using the current date as the backup folder name (YYYYMMDD)

Originally published at https://jasonwatmore.com
Backup MongoDB database using date for the folder name

The mongodump command will create a backup / dump of the MongoDB database with the name specified by the --db [DB NAME] argument.

The --out /var/backups/`date +"%Y%m%d" argument specifies the output directory as /var/backups/[TODAY'S DATE] e.g. /var/backups/20190903.

sudo mongodump --db [DB NAME] --out /var/backups/`date +"%Y%m%d"`
Restore MongoDB database from backup

The mongorestore command restores a database to the destination --db [DB NAME] from the specified directory, e.g. /var/backups/20190903.

sudo mongorestore --db [DB NAME] /var/backups/[BACKUP FOLDER NAME]

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

MongoDB - The Complete Developer’s Guide

The Complete Developers Guide to MongoDB

Learn MongoDB : Leading NoSQL Database from scratch

Learn NoSQL Databases - Complete MongoDB Bootcamp 2019

MongoDB Connection Initialization – Node.js API with TDD Tutorial

Building a simple app using NodeJS, MongoDB, and ExpressJS

Node, Express, React.js, Graphql and MongoDB CRUD Web Application

Building REST API with Nodejs / MongoDB /Passport /JWT

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB - Part 3/3

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB

What you’ll learn

  • Work with MongoDB with Clarity and Confidence
  • Use 4 tools MongoCHEF, NOSQL Manager, RoboMongo, MongoBooster easily
  • Do Regex, GridFS , Replication , Sharding, Full text search
  • Basic and Advanced CRUD operations using MongoDB
  • Import and Export data from MongoDB
  • Work MapReduce, Embedded Documents,Save&Insert , indexing, capped collections, TTL
  • Bonus section * Use java,C#,PHP,Nodejs to access MongoDB features like CRUD, GridFS
  • Bonus Section * A 50 minutes MongoDB key feature exercises
  • 100+ Quizzes 40+ Activities

Learn More

MongoDB - The Complete Developer’s Guide

The Complete Developers Guide to MongoDB

MongoDB - The Complete Developer’s Guide

Learn MongoDB : Leading NoSQL Database from scratch

Learn NoSQL Databases - Complete MongoDB Bootcamp 2019

Build a CRUD Operation using PHP & MongoBD

MongoDB with Python Crash Course - Tutorial for Beginners

Learn NoSQL Databases from Scratch - Complete MongoDB Bootcamp 2019

AngularJS tutorial for beginners with NodeJS, ExpressJS and MongoDB

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Creating RESTful APIs with NodeJS and MongoDB Tutorial