How to create a MongoDB Replica Set in macOS Local Environment


Install and run MongoDB with Homebrew

  • The first step is updating Homebrew. Open the Terminal application and type: brew update
  • After updating Homebrew: brew install mongodb
  • After downloading Mongo, create the db directory. This is where the Mongo data files will be stored: mkdir-p /data/db
  • Make sure that the /data/db directory has the right permissions by running: sudo chown -R `id -un` /data/db

Creating the Replica Set

  1. In different terminals, we can start three nodes for the Replica by running:
mongod --port 27017 --dbpath /data/db/rs0-0 --replSet rs0 --bind_ip localhost

mongod --port 27018 --dbpath /data/db/rs0-1 --replSet rs0 --bind_ip localhost

mongod --port 27019 --dbpath /data/db/rs0-2 --replSet rs0 --bind_ip localhost

2. For the next step, we need to open a mongo shell that connects to the primary node by using the mongo command and run:

        _id: "rs0",
        members: [
            { _id: 0, host : "" },
            { _id: 1, host : "" },
            { _id: 2, host : "" }


Sometimes, one of the common MongoDB ports might be already in use. In order to find the process that is running on a specific ports, we can run:

lsof -n -i :<port-number> | grep LISTEN

This will provide us the process id, which we can kill later by running:

kill -9 <process-id>