This section introduces the installation of MongoDB Community Edition in the Docker environment.

Suggestion: For development environment, it is recommended to use Docker to install MongoDB. One-click installation is fast, you can just turn it off when not in use, and it also facilitates the maintenance of multiple development environments, avoiding installing everything on your computer.

Prerequisites

Docker is already installed.

Installing MongoDB with Docker

MongoDB Docker image repository address:

https://hub.docker.com/_/mongo/

Command to install and start MongoDB:

docker run --name mongo \
	-p 27017:27017 \
	-v /Users/tizi365/Documents/work/local/mongo-data:/data/db \
	-e MONGO_INITDB_ROOT_USERNAME=tizi365 \
    -e MONGO_INITDB_ROOT_PASSWORD=123456 \
	-d \
	mongo:4.4.5

Explanation of command parameters:

  • --name: The name of the container, in this case it's "mongo".
  • -p: Maps the container's 27017 port to the local 27017 port, so that we can access MongoDB in the container from our computer.
  • -v: Persists MongoDB data to the /Users/tizi365/Documents/work/local/mongo-data directory. You can change it to your own directory. Make sure to set this parameter, otherwise the MongoDB data will be lost after restarting the container.
  • MONGO_INITDB_ROOT_USERNAME: Sets the default account of MongoDB to "tizi365".
  • MONGO_INITDB_ROOT_PASSWORD: Sets the default password of MongoDB to "123456".
  • -d: Switches the container to run in the background.
  • mongo:4.4.5: Uses the mongo image version 4.4.5. For other versions, you can check the repository link provided earlier for updated version tags.

Starting MongoDB

After installing and starting MongoDB earlier, if the container is turned off after you restart your computer, you can use the following command to restart mongo:

docker start mongo 

Stopping MongoDB

docker stop mongo