Skip to content

#4 Install and config MongoDB on Mac and Docker

There are multiple methods to install MongoDB on your local environment. You can check the official page and follow the instructions.

If your environment is Windows, the installation will be very easy and can be finished by a few clicks.

My environment is MacOs and my experience of installation is not sweet or smooth. However, I found a way to make the procedure easy — by installing the MongoDB on Docker. Docker containers provide isolated environments for running applications. By running MongoDB in a container, I can ensure that its dependencies are contained within the container itself, avoiding conflicts with other applications on the host system.

Install MongoDB on Docker

1. Prerequisite

  1. Install Docker: https://docs.docker.com/get-docker/
  2. Install Mongosh: https://www.mongodb.com/docs/mongodb-shell/install/

2. Pull the MongoDB Docker Image

There are many versions of MongoDB Community and I suggest you use the latest version.

docker pull mongodb/mongodb-community-server:latest

3. Run the Image as a Container

The -p 27017:27017 in this command maps the container port to the host port. This allows you to connect to MongoDB with a localhost:27017 connection string.

docker run --name mongodb -p 27017:27017 -d mongodb/mongodb-community-server:latest

4. Check that the Container is Running

docker container ls

5. Connect to the MongoDB Deployment with mongosh

mongosh --port 27017

Option: Install the MongoDB Compass

If you prefer the Graphic User Interface, you can install the MongoDB Compass, which provides users with a way to visually explore their MongoDB databases, making it easier to understand the structure of their data, run queries, and perform various administrative tasks.

Install MongoDB on Mac

1. Install the Xcode command-line tools and Homebrew

xcode-select --install
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

2. Install MongoDB 6.0 Community Edition

brew tap mongodb/brew
brew update
brew install mongodb-community@6.0     # you can change the version e.g 7.0

3. Run MongoDB Community Edition

# run 
brew services start mongodb-community@6.0
#stop
brew services stop mongodb-community@6.0

4. Solve Exit Issues

If you have met the the issue “exit code 5” and the information looks like this

mongodb-community error   root /Library/LaunchDaemons/homebrew.mxcl.mongodb-community.plist

You can do this to solve the exit issue.

rm ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
brew services restart mongodb-community@6.0       #restart

5. Verify the Running

brew services list      

#the result
Name                  Status         User File
mongodb-community@6.0 started ivyw ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community@6.0.plist