/ Getting Started

How to install Mongo in macOS/Linux with Homebrew

Install Mongo in macOS/Linux

1. Install Homebrew

Homebrew is a Package Manager for macOS/Linux.
Go to https://brew.sh/ and find a command for installing Homebrew and run in your Terminal prompt.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)”

(optional) Install node js with brew by the line below if you need: brew install node

2. Setup a custom Homebrew tap and install mongo

Add a custom tap: brew tap mongodb/brew
And install mongo: brew install mongodb-community

Homebrew will create the conf file and paths below as defaults.

  • the configuration file: /usr/local/etc/mongod.conf
  • the log directory path: /usr/local/var/log/mongodb
  • the data directory path: /usr/local/var/mongodb

To run mongod as a service, brew services start mongodb-community.
To stop the server, brew services stop mongodb-community.

It uses the default conf file and paths for mongodb and the log.

To verify that MongoDB has started successfully: ps aux | grep -v grep | grep mongod

To connect and use MongoDB, open a new Terminal and run mongo. MongoDB shell is now up and running!

Set mongo db and log path manually

- Troubleshooting errors for beginners and macOS Catalina

If you get the exception similar to below, you will need to create a directory for mongo data with following command: sudo mkdir -p /data/db

exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating

BUT you might get the another error, mkdir: /data/db: Read-only file system. That might be because you are using macOS Catalina.

Starting with macOS 10.15 Catalina, Apple restricts access to the MongoDB default data directory of /data/db. On macOS 10.15 Catalina, you must use a different data directory, such as /usr/local/var/mongodb.

Since you cannot create directories in root system, create the db directory with sudo mkdir -p /Users/YOUR_USER_NAME/data/db.

Tip: Find out your username by running this command: whoami

And create the log directory: sudo mkdir -p /Users/jadekim/data/log/db

Then run mongod manually by setting up the db and log path with following command.

mongod --dbpath=/Users/jadekim/data/db --logpath=/Users/jadekim/data/log/db/mongo.log

But you might still get another error.

exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: /Users/jadekim/data/db, terminating

We need to set permissions for the data and log directories: sudo chown -Rv YOUR_USER_NAME /Users/YOUR_USER_NAME/data/db

In my case: sudo chown -Rv jadekim /Users/jadekim/data/db

Finally, you can run mongod successfully!

mongod --dbpath=/Users/jadekim/data/db --logpath=/Users/jadekim/data/log/db/mongo.log

Open a new Terminal and run mongo.