Install MongoDB on macOS with Homebrew and CRUD operations

Video thumbnail

Let's learn how we can install MongoDB if we are on macOS; for this, we will start with the assumption that you have Homebrew installed, which is simply a package manager for macOS and Linux.

Perform some practices to use a NoSQL database, specifically MongoDB, in FastAPI. Before starting, we will compare MongoDB with traditional relational (SQL) databases.

SQL vs. NoSQL

  • Relational Databases (SQL): As we have seen so far, they are structured. They function like Excel tables linked to each other. They have a fixed schema; for example, if you have a "tasks" table with ID and Name, and then you want to save a Description, you must mandatory modify the database schema.
  • NoSQL Databases (MongoDB): These are unstructured (or semi-structured) databases. Data is stored in a flexible way, generally in formats similar to JSON. This allows changing the structure without prior notice. For example, we can inject a "category" directly into the schema of a "task".

Advantages and Disadvantages

Advantages:

  • Flexibility: Ideal for rapid prototyping and changing schemas.
  • Massive scalability: Designed to handle gigantic volumes of data.
  • Speed: They tend to be more efficient for simple read/write operations.

Disadvantages:

  • Less consistency: By not having a fixed schema, they can become a mess if not managed well.
  • Complex queries: It is more difficult to perform joins or very intricate queries.
  • Maturity: Although they are popular, the SQL ecosystem has decades more of support and stability.

Installation on Windows

Installation on Windows is very simple:

  1. Search Google for MongoDB Community Server.
  2. Download the installer and follow the typical steps (Next, Next, Finish).
  3. Environment variables configuration: You will likely need to add the installation path (usually the bin folder) to the system environment variables.
    1. Tip: Right-click on "This PC" -> Properties -> Advanced system settings -> Environment Variables -> Path -> Add the bin folder path.
  4. Restart your computer and you will be able to use the mongosh command.

Installation on macOS (using Homebrew)

Installing MongoDB on macOS might seem complicated the first time, but using Homebrew makes the process much simpler and cleaner. In this guide, I explain step-by-step how to install MongoDB on macOS with Homebrew, how to start it correctly, and how to begin working with the database by performing basic CRUD operations.

This flow is the one I always use whenever I set up a new development environment on Mac, and it avoids most of the typical errors that usually appear when starting MongoDB for the first time.

With our package manager ready, nothing could be easier; the first thing we need to do is add the MongoDB repository to our package manager.

Prerequisites

Before installing MongoDB, it is important to ensure that the system has everything it needs.

Compatible macOS

MongoDB works correctly on modern versions of macOS (Catalina onwards). If you are using a very old version, it is recommended to update the system or install a compatible version of MongoDB.

Homebrew Installation

macOS does not include Homebrew by default, and it is one of the most important tools for development on Mac. Homebrew is a package manager that allows you to install software from the terminal easily.

To install it, follow the official instructions from their website:

https://brew.sh/#install

Necessary software to install MongoDB

Install Command Line Tools for Xcode

Most likely, when you go to execute the Brew command to install the package, it will ask you to install the Command Line Tools for Xcode; accept, download, and install these tools.

It is very probable that, when executing any brew command, macOS will ask you to install the Command Line Tools for Xcode.

Accept the message and let them install, as they are necessary to compile and run many dependencies.

Install Homebrew

What is a Homebrew tap?

A tap is simply an additional repository that Homebrew uses to find packages. MongoDB maintains its official tap, which is important to avoid unsupported installations.

Command to add the tap

Now then, let's install Homebrew. macOS does not include the Homebrew preparation package by default; therefore, you have to install it as indicated on the official page. https://brew.sh/#install

Homebrew installs the things you need for your macOS from a terminal easily.

$ brew tap mongodb/brew

This step is key; many errors come from trying to install MongoDB without using the official tap.

Choosing the MongoDB version

MongoDB publishes several versions. In this case, we are going to install a specific stable version, which is the one that has given me the best results on macOS:

Install the MongoDB Homebrew Tap

Issue the following from the terminal to tap the official MongoDB Homebrew tap: https://github.com/mongodb/homebrew-brew

This is a custom Homebrew Tap (package) for official MongoDB software.

$ brew tap mongodb/brew

After this, we install the latest version to date, which at the time of saying these words would be:

$ brew install mongodb-community@8.2

Or you can install a specific version

$ brew install mongodb-community@8.0
$ brew install mongodb-community@7.0

Installing a specific version avoids incompatibilities with libraries or the operating system, something that has already saved me more than one headache.

Graphical Interface: MongoDB Compass

To work in a more pleasant way and not depend only on the terminal, we will install MongoDB Compass, the official graphical interface tool.

  • On Windows: It can be selected during the server installation or downloaded separately from the official website.
  • On macOS (via Homebrew):
    • $ brew install --cask mongodb-compass
    • (The --cask parameter indicates that we are installing an application with a graphical interface).

Once installed, you will find it in your Applications folder. Open it, connect to the local server, and you will be ready to manage your data collections.

You can also install it using the installer on macOS and Windows:

https://www.mongodb.com/try/download/compass

Checking the MongoDB Installation

Once the process is finished, MongoDB will be installed on your computer, but it will not be running yet.

Starting the MongoDB Process

Now that we have MongoDB on our computer, the next thing we are going to do is start the process, because if we run in our terminal:

$ brew services start mongodb-community

This command is fundamental. If you don't start the service and run mongo directly, you will get a connection error.

Because if you don't start it and type mongo in the terminal, you will see an error like the following:

MongoDB shell version v8.0.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:372:17

This happens because MongoDB is not listening on port 27017.

Once successfully started, the command:

$ mongo

Will allow you to access the shell without problems, or see its installed version:

$ mongod --version

Starting the Service

Just like with services like MySQL, to be able to use it, we must start the service; because if we try to start the Mongo assistant without starting the service:

$ mongosh

We will see an error like the following:

Current Mongosh Log ID: 699c28e47c1b4855cf41cae5
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.7.0
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

Which says it's trying to connect but the MongoDB server DID NOT respond; we start the service:

brew services start mongodb-community@8.2

And now, if you run:

$ mongosh

It should greet you with a:

test>

Stopping or Restarting MongoDB

Some useful commands I usually use:

$ brew services stop mongodb-community
$ brew services restart mongodb-community

⚠️ Common Errors and How to Resolve Them

Connection error on localhost

It is almost always because the service is not started. Verify with:

$ brew services list

Incompatible Version Issues

If you changed your macOS version or updated MongoDB, it might be necessary to reinstall the correct version or clean up old services.

First steps with MongoDB (Basic CRUD)

Perform CRUD Operations with MongoDB

Let's learn how we can perform CRUD operations using MongoDB; remember that CRUD operations are those that allow us to Create, Read, Update, and Delete respectively.

Create operations

Create or insertion operations add new documents to a collection. If the collection does not currently exist, the insertion operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:

db.collection.insertOne() 
db.collection.insertMany()

Example operations:

var user2 = {
   name: 'Andres',
   last_name: 'Cruz',
   age: 29,
   email: 'andres@gmail.com'
}
var user3 = {
   name: 'Pablo',
   last_name: 'Lama',
   age: 30,
   email: 'pablo@gmail.com'
}
var user4 = {
   name: 'Luis',
   last_name: 'Yello',
   age: 99,
   email: 'pepe@gmail.com'
}
db.users.insertOne(user2)
db.users.insertMany(
   [user3, user4, user2]
)

Which allow inserting a single record or more than one respectively.

Read operations

Read operations retrieve documents from a collection; that is, they query a collection of documents. MongoDB provides the following operation to read documents from a collection:

db.collection.find()
Operaciones de ejemplo:
db.users.find(
   { age: 25 },
   { name: true, email: true, _id: false }
).pretty()
db.users.find(
   { age: 25 },
   { email: false, _id: false }
).pretty()

Update operations

Update operations modify existing documents in a collection. MongoDB provides the following methods to update documents in a collection:

db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()

Example operations:

db.users.updateMany(
   {
       name: {
           $exists: true
       }
   },
   {
       $set: {
           name2: "Luisito"
       }
   }
)
db.users.updateOne(
   {
       name: {
           $exists: true
       }
   },
   {
       $unset: {
           name2: "Luisito"
       }
   }
)

Delete operations

Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents from a collection:

db.collection.deleteOne()
db.collection.deleteMany()

Example operations:

db.users.deleteOne({"_id": new mongo.ObjectID(id) })
db.users.deleteMany({"_id": new mongo.ObjectID(id) })

Additional tips and best practices

  • Always use the official MongoDB tap
  • Install specific versions to avoid incompatibilities
  • Don't forget to start the service before using the shell
  • For production environments, enable authentication and backups
Learn how to install MongoDB on macOS using Homebrew, step by step. This updated guide covers common errors, service startup, and CRUD examples to help you get started.

I agree to receive announcements of interest about this Blog.

Andrés Cruz

ES En español