Table of Contents
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:
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:
So, I can execute inside the container by issuing the following command:
docker exec -it bbc5a637b0e6 bash
Inside the container, type
mongo and you can access the mongo shell
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.
Basic MongoDB commands cheat sheet
To clear the screen type:
And hit enter
To show available databases, type:
To use a particular database, type:
One important note here: There is no create database command in MongoDB. You can “create” one by simply using the
To show all documents in a collection, type:
db.<collectionName>.find() # For example: db.friends.find()
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.
I build softwares that solve problems. I also love writing/documenting things I learn/want to learn.