Setup MongoDB Test Environment With Docker

This tutorial helps you quickly setup a MongoDB instance so you can start learning this topic right away.

We are going to use MongoDB 5 in this series. I haven’t tested with other versions so if you are from the past or the future, make sure you use the correct version as in this post.

Running MongoDB with docker

If you have Docker installed, running MongoDB is really easy:

docker run -dit --restart=always -p 27017:27017 mongo:5.0

Here, I mapped the port 27017 of MongoDB to the port 27017 of the host. If your host doesn’t have the port 27017 available, change that number to a different number.

You only need to do the port mapping if you want to connect to the instance using clients such as MongoDB Compass. If you use the shell (as I’m going to), you just need to run this:

docker run -dit --restart=always mongo:5.0

I run the container in detach mode and make it always restart for convenient.

Let’s check if the instance is running:

docker ps
Running mongoDB with docker
Running mongoDB with docker

As you can see, I have already setup one instance and it’s available there.

You should be able to see your instance as well.

Connect to the MongoDB Shell inside Docker container

As mentioned above, I’m not going to use a client but the MongoDB shell inside the docker container. From the docker ps command’s output, I know that the container id is: bbc5....

So, I can execute inside the container by issuing the following command:

docker exec -it bbc5a637b0e6 bash
Exec into MongoDB docker container

Inside the container, type mongo and you can access the mongo shell

The mongo shell
The mongo shell

MongoDB Hierachy

In MongoDB, at the top level, you have databases. Inside databases, there are collections. Inside collections, you have documents.

Documents are JSON objects that contain keys and values.

MongoDB hierachy
MongoDB hierachy

Basic MongoDB commands cheat sheet

To clear the screen type:

cls

And hit enter

To show available databases, type:

show dbs
Show mongo databases
Show mongo databases

To use a particular database, type:

use <dbname>
Use a database
Use a database

One important note here: There is no create database command in MongoDB. You can “create” one by simply using the use command.

To show all documents in a collection, type:

db.<collectionName>.find()
# For example:
db.friends.find()
Listing documents in MongoDB collections
Listing documents in MongoDB collections

Conclusion

In this post, I’ve shown you how to setup MongoDB and do some basic queries. We are going to learn more about MongoDB in the next articles.

Leave a Comment