Using MongoDB

Learn how to use MongoDB.

Introduction

There are many ways to use the MongoDB Server.

Use MongoDB on a local machine

MongoDB can be used locally. To learn how to install MongoDB, be sure to check the MongoDB installation guide.

Use MongoDB with Docker

We follow the steps below to use MongoDB with Docker:

  1. Pull the MongoDB image.

    docker pull mongo
    
  2. Create a container to start the MongoDB server.

    docker run -itd --name mongodb -v /your/volume/mongodb-volume:/data/db -p 27017:27017 mongo
    

In the commands above, we use the following command arguments:

  • -itd means the container is created with interactive and TTY mode (marked with it). The container is detached (marked with d) so the container can run in the background.
  • --name means the container is created with a specific name. In this command, the name of the container is mongodb.
  • -v means the container is created with the volume to ensure the storage in MongoDB is persistent. If the container is stopped, the data inside the server still exists. The local storage is mapped in /your/volume/mongodb-volume to the container storage in /data/db.
  • -p means the container must be exposed to the local network with port 27017. This port is mapped into the container port that uses 27017.
  • mongo means the container uses mongo as the image.

Note: To stop the MongoDB server, use docker container stop MongoDB.

To start the MongoDB server, use docker container start mongodb.

Get hands-on with 1400+ tech skills courses.