You don't need a separate database to support transactions, rich search, or gen AI. The world's most popular document database is now the world's most versatile developer data platform.

Built by developers, for developers

The document data model maps to how you think and code. Break out of rigid, tabular data structures with flexible documents that map directly to objects in your code. Embed related data into a single document to increase performance and minimize computational cost.

MongoDB: A JSON Document Database

MongoDB is an open-source, cross-platform, document-oriented database management system. MongoDB stores data as a series of JSON-like documents (actually stored as binary JSON, or BSON), as opposed to the table and row format of relational databases. This flexible approach to storing data makes it particularly suitable for developers who may not be database experts, yet want to use a database to support the development of their applications.

Instead of having multiple tables you can simply keep all of your related data together. This makes reading your data very fast.

You can still have multiple groups of data too. In MongoDB, instead of tables these are called collections.

Some structure can optionally be enforced on JSON documents through schemas.


MongoDB is developed by MongoDB Inc.

MongoDB Features

Ad-hoc queries
MongoDB supports field, range query and regular-expression searches. Queries can return specific fields of documents and also include user-defined JavaScript functions. Queries can also be configured to return a random sample of results of a given size.
Indexing
Fields in a MongoDB document can be indexed with primary and secondary indexes.
Replication

MongoDB provides high availability with replica sets. A replica set consists of two or more copies of the data. Each replica-set member may act in the role of primary or secondary replica at any time. All writes and reads are done on the primary replica by default. Secondary replicas maintain a copy of the data of the primary using built-in replication. When a primary replica fails, the replica set automatically conducts an election process to determine which secondary should become the primary. Secondaries can optionally serve read operations, but that data is only eventually consistent by default.

If the replicated MongoDB deployment only has a single secondary member, a separate daemon called an arbiter must be added to the set. It has the single responsibility of resolving the election of the new primary. As a consequence, an ideal distributed MongoDB deployment requires at least three separate servers, even in the case of just one primary and one secondary.

Load balancing

MongoDB scales horizontally using sharding. The user chooses a shard key, which determines how the data in a collection will be distributed. The data is split into ranges (based on the shard key) and distributed across multiple shards, which are masters with one or more replicas. Alternatively, the shard key can be hashed to map to a shard–enabling an even data distribution.

MongoDB can run over multiple servers, balancing the load or duplicating data to keep the system functional in case of hardware failure.

File storage

MongoDB can be used as a file system, called GridFS, with load-balancing and data-replication features over multiple machines for storing files.

This function, called a grid file system, is included with MongoDB drivers. MongoDB exposes functions for file manipulation and content to developers. GridFS can be accessed using the mongofiles utility or plugins for Nginx and lighttpd. GridFS divides a file into parts, or chunks, and stores each of those chunks as a separate document.

Aggregation

MongoDB provides three ways to perform aggregation: the aggregation pipeline, the map-reduce function and single-purpose aggregation methods.

Map-reduce can be used for batch processing of data and aggregation operations. However, according to MongoDB's documentation, the aggregation pipeline provides better performance for most aggregation operations.

The aggregation framework enables users to obtain results similar to those returned by queries that include the SQL GROUP BY clause. Aggregation operators can be strung together to form a pipeline, analogous to Unix pipes. The aggregation framework includes the $lookup operator, which can join documents from multiple collections, as well as statistical operators such as standard deviation.

Server-side JavaScript execution
JavaScript can be used in queries, aggregation functions (such as MapReduce) and sent directly to the database to be executed.
Capped collections
MongoDB supports fixed-size collections called capped collections. This type of collection maintains insertion order and, once the specified size has been reached, behaves like a circular queue/buffer.
Transactions
MongoDB supports multi-document ACID transactions since the 4.0 release in June 2018.

MongoDB Community Server (Free)

The Community version of MongoDB distributed database offers a flexible document data model along with support for ad-hoc queries, secondary indexing, and real-time aggregations to provide powerful ways to access and analyze your data.

The database is also offered as a fully-managed service with MongoDB Atlas. Get access to advanced functionality such as auto-scale, full-text search, and data distribution across regions and clouds. Deploy in minutes on AWS, Google Cloud, and/or Azure, with no downloads necessary.


Give it a try with a free, highly-available 512 MB cluster. or get started from your terminal with the following two commands:

$ sudo apt-get install mongodb-atlas
$ atlas setup

Installation

MongoDB can be installed locally, which will allow you to host your own MongoDB server on your hardware. This requires you to manage your server, upgrades, and any other maintenance.

You can download and use the MongoDB open source Community Server (at https://www.mongodb.com/try/download/community) on your hardware for free.

To install on a Linux (Ubuntu) machine, go to section Install Official MongoDB Packages on Ubuntu.

Atlas (Cloud)

You may use MongoDB Atlas, a cloud database platform. This is much easier than hosting your own local database.

Sign up for a free MongoDB Atlas account (at https://www.mongodb.com/try) to get started!

Create a database user

After a shortish procedure, I choose a Free scheme with 512MB storage, name franciscofvh, leave options [v] automate security setup and [v] preload sample dataset, as well as default provider AWS. I also create my first tag...

From an email message I somehow land at https://account.mongodb.com/account/profile/overview and click to visit MongoDB Atlas (https://cloud.mongodb.com/user/detectSession)

We autogenerated a username and password. You can use this or create your own.

This first user will have atlasAdmin permissions for this project.

You'll need your database user's credentials in the next step. Copy the database user password.

Username: franciscofvh

Password: UbJMA7s1VBrDwWBn

Procedure for Connecting

  1. Go to https://cloud.mongodb.com/user/detectSession and type your username and password (shambhalatlas) to log in (Compass or GUI)

  2. Add a connection IP address by just clicking a box at the top

    Your current IP address (say, 80.39.56.130) has been added to enable local connectivity. Only an IP address you add to your Access List will be able to connect to your project's clusters. Add more later in Network Access

    You are already logged into your MongoDB account in the cloud and using the Compass GUI.

  3. While there, if you want to use the command line interface (mongosh)

    1. first obtain a connection string by clicking on the Connect box. This will cause a pop up window to appear, where you should choose to Access your data through tools: Shell (the second out of four options)
    2. Select your mongosh version: just run mongosh --version on a terminal
    3. Copy (to the clipboard) the connection string that you can see below (in the bottom half of the pop-up window)
    4. Then, to access your MongoDB Atlas database(s) on the command line (mongosh) type:

      mongosh "mongodb+srv://franciscofvh.a9syx.mongodb.net/" --apiVersion 1
      --username franciscofvh - -password a55MIz2hOWLBvuE9

      If you don't specify your password on the command line (mongosh <connection_string>), you will be requested for one...

      so type or paste a55MIz2hOWLBvuE9 and press ENTER.

    5. Perhaps you shouldn't close the connection window (Compass GUI)

Windows

I download the prerequisite zip file. The unzipped directory contains:

  • mongod The database server.
  • mongos Sharding router.
  • mongo The database shell (uses interactive javascript).

Procedure

Follow these steps to install MongoDB Community Edition using the MongoDB Installer wizard. The installation process installs both the MongoDB binaries as well as the default configuration file install directory\bin\mongod.cfg.

Download the installer.

Download the MongoDB Community .msi installer from the following link:

MongoDB Download Center

https://www.mongodb.com/try/download/community?tck=docs_server

  • In the Version dropdown, select the version of MongoDB to download.
  • In the Platform dropdown, select Windows.
  • In the Package dropdown, select msi.
  • Click Download.
Run the MongoDB installer.

For example, from the Windows Explorer/File Explorer:

  • Go to the directory where you downloaded the MongoDB installer (.msi file). By default, this is your Downloads directory.
  • Double-click the .msi file.
Follow the MongoDB Community Edition installation wizard.

The wizard steps you through the installation of MongoDB and MongoDB Compass.

Choose Setup Type:

You can choose either the Complete (recommended for most users) or Custom setup type. The Complete setup option installs MongoDB and the MongoDB tools to the default location. The Custom setup option allows you to specify which executables are installed and where.

Service Configuration

You can set up MongoDB as a Windows service during the install or just install the binaries.

MongoDB Service

MongoDB

You can configure and start MongoDB as a Windows service during the install, and the MongoDB service is started upon successful installation.

Select Install MongoDB as a Service.

Select one of these options:

- Run the service as Network Service user (Default)

This is a Windows user account that is built-in to Windows.

- Run the service as a local or domain user

For an existing local user account, specify a period (.) for the Account Domain and specify the Account Name and the Account Password for the user.

For an existing domain user, specify the Account Domain, Account Name and Account Password for that user.

Service Name. Specify the service name. Default name is MongoDB. If you already have a service with the specified name, you must choose another name.

Data Directory. Specify the data directory, which corresponds to the --dbpath. If the directory does not exist, the installer will create the directory and sets the directory access to the service user.

Log Directory. Specify the Log directory, which corresponds to the --logpath. If the directory does not exist, the installer will create the directory and sets the directory access to the service user.

Compass on Windows*

Install and Run mongosh on Windows

The .msi installer does not include mongosh. Follow the mongosh installation instructions (at https://www.mongodb.com/docs/mongodb-shell/install/) to download and install the shell separately.

Prerequisites

To use the MongoDB Shell, you must have a MongoDB deployment to connect to.

  • For a free cloud-hosted deployment, you can use MongoDB Atlas.
  • To learn how to run a local MongoDB deployment, see Install MongoDB.
Add the mongosh binary to your PATH environment variable.

Ensure that the extracted MongoDB Shell binary is in the desired location in your filesystem, then add that location to your PATH environment variable.

To add the MongoDB Shell binary's location to your PATH environment variable:

  1. Open the Control Panel.
  2. In the System and Security category, click System.
  3. Click Advanced system settings. The System Properties modal displays.
  4. Click Environment Variables.
  5. In the System variables section, select Path and click Edit. The Edit environment variable modal displays.
  6. Click New and add the filepath to your mongosh binary.
  7. Click OK to confirm your changes. On each other modal, click OK to confirm your changes.

To confirm that your PATH environment variable is correctly configured to find mongosh, open a command prompt and enter the mongosh --help command. If your PATH is configured correctly, a list of valid commands displays.

Next Steps... Connect [to a Local Deployment on the Default Port]!

Once you have successfully install mongosh, learn how to connect to your MongoDB deployment.

To connect to a MongoDB deployment running on localhost with default port 27017, run mongosh without any options:

mongosh

This is equivalent to the following command:

mongosh "mongodb://localhost:27017"

Install Official MongoDB Packages on Ubuntu

To install MongoDB Community on your Ubuntu system, these instructions will use the official mongodb-org package, which is maintained and supported by MongoDB Inc. The official mongodb-org package always contains the latest version of MongoDB, and is available from its own dedicated repo.

Follow these steps to install MongoDB Community Edition using the apt package manager.

  1. Import the Public Key

    From a terminal, install gnupg and curl if they are not already available:

    sudo apt-get install gnupg curl

    To import the MongoDB public GPG key, run the following command:

    curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
    sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
    --dearmor
  2. Create the List File

    Create the list file /etc/apt/sources.list.d/mongodb-org-8.0.list for your version of Ubuntu.

    You can find your version of Ubuntu by running

    cat /etc/lsb-release

    Create the list file for Ubuntu 24.04 (Noble):

    echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
  3. Reload the Package Database

    Issue the following command to reload the local package database:

    sudo apt-get update
  4. Install MongoDB Community Server

    You can install either the latest stable version of MongoDB or a specific version of MongoDB.

    To install the latest stable version, issue the following

    sudo apt-get install -y mongodb-org

Basic Administration of MongoDB (Community Edition)

ulimit Considerations

Most Unix-like operating systems limit the system resources that a process may use. These limits may negatively impact MongoDB operation, and should be adjusted. See UNIX ulimit Settings for Self-Managed Deployments for the recommended settings for your platform.

Directories

If you installed through the package manager, the data directory /var/lib/mongodb and the log directory /var/log/mongodb are created during the installation.

By default, MongoDB runs using the mongodb user account. If you change the user that runs the MongoDB process, you must also modify the permission to the data and log directories to give this user access to these directories.

Configuration File

The official MongoDB package includes a configuration file (/etc/mongod.conf). These settings (such as the data directory and log directory specifications) take effect upon startup. That is, if you change the configuration file while the MongoDB instance is running, you must restart the instance for the changes to take effect.

Procedure

Follow these steps to run MongoDB Community Edition on your system. These instructions assume that you are using the official mongodb-org package -- not the unofficial mongodb package provided by Ubuntu -- and are using the default settings.

Init System

To run and manage your mongod process, you will be using your operating system's built-in init system. Recent versions of Linux tend to use systemd (which uses the systemctl command), while older versions of Linux tend to use System V init (which uses the service command).

If you are unsure which init system your platform uses, run the following command:

ps --no-headers -o comm 1

Then select the appropriate tab below based on the result:

  • systemd - select the systemd (systemctl) tab below.
  • init - select the System V Init (service) tab below.
  1. Start MongoDB

    You can start the mongod process by issuing the following command:

    sudo systemctl start mongod

    If you receive an error similar to the following when starting mongod:

    Failed to start mongod.service: Unit mongod.service not found.

    Run the following command first:

    sudo systemctl daemon-reload

    Then run the start command above again.

  2. Verify that MongoDB has started successfully.

    sudo systemctl status mongod

    You can optionally ensure that MongoDB will start following a system reboot by issuing the following command:

    sudo systemctl enable mongod
  3. Stop MongoDB

    As needed, you can stop the mongod process by issuing the following command:

    sudo systemctl stop mongod
  4. Restart MongoDB

    You can restart the mongod process by issuing the following command:

    sudo systemctl restart mongod

    You can follow the state of the process for errors or important messages by watching the output in the /var/log/mongodb/mongod.log file.

  5. Begin using MongoDB.

    Start a mongosh session on the same host machine as the mongod. You can run mongosh without any command-line options to connect to a mongod that is running on your localhost with default port 27017.

    For more information on connecting using mongosh, such as to connect to a mongod instance running on a different host and/or port, see the mongosh documentation.

    To help you start using MongoDB, MongoDB provides Getting Started Guides in various driver editions. For the driver documentation, see Start Developing with MongoDB.

Compass: the GUI for MongoDB

Compass is a free interactive tool for querying, optimizing, and analyzing your MongoDB data. Get key insights, drag and drop to build pipelines, and more.

Read the documentation at https://www.mongodb.com/docs/compass/current/.

Special Cases

Failure (illegal instruction) Because CPU does not support AVX

Running sudo service mongod status yields

oct 23 16:27:36 francisco-hpnotebook systemd[1]: \
Started mongod.service - MongoDB Database Server.
oct 23 16:27:37 francisco-hpnotebook systemd[1]: \
mongod.service: Main process exited, code=dumped, status=4/ILL
oct 23 16:27:37 francisco-hpnotebook systemd[1]: \
mongod.service: Failed with result 'core-dump'.

The signal=ILL part of the systemctl output means that MongoDB failed to start because of an illegal instruction. This is caused by MongoDB 5 and later requiring AVX to run.

You can check if your CPU supports AVX by execting:

cat /proc/cpuinfo | grep avx

If you get any kind of output your CPU should support AVX, if not its either too old or if you are running Linux inside a VM and your hypervisor isn't passing through your physical CPU flags. For a list of CPUs that support AVX see: https://en.wikipedia.org/wiki/Advanced_Vector_Extensions (basically CPUs started supporting AVX at around 2011)

If your physical CPU is indeed too old your options are:

  • Downgrade to MongoDB 4 which still runs without AVX but will be end of life next year
  • Compile your own version of MongoDB without AVX or look around for community made version without AVX (there are some unoffical containers out there for example)
  • If you are using virtualization make sure your hypervisor isn't hiding your physical CPU flags for compability or other reasons
  • If your hardware is indeed too old to support AVX upgrade to a newer CPU

Reinstalling on Linux (Ubuntu)

  1. Stop the mongod process by issuing the following command:

    sudo service mongod stop
  2. Remove any MongoDB packages that you had previously installed:

    sudo apt-get purge mongodb-org*
  3. Remove MongoDB databases and log files:

    sudo rm -r /var/log/mongodb
    sudo rm -r /var/lib/mongodb
  4. To install, import the public key used by the package management system:

    wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
  5. I check my version of Ubuntu by running lsb_release -a

  6. The following instruction is for Ubuntu 20.04.01 (code name noble):

    echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
  7. Update Apt

    sudo apt-get update
  8. Install mongodb

    sudo apt-get install mongodb-org mongodb-org-server mongodb-org-shell mongodb-org-mongos mongodb-org-tools

    Alternatively, for versions not demanding AVX (a CPU set of instructions) choose version 4*:

    sudo apt-get install mongodb-org=4.4.8 mongodb-org-server=4.4.8 mongodb-org-shell=4.4.8 mongodb-org-mongos=4.4.8 mongodb-org-tools=4.4.8

    or just

    sudo apt-get install mongodb-org=4.4 mongodb-org-server=4.4 mongodb-org-shell=4.4 mongodb-org-mongos=4.4 mongodb-org-tools=4.4
  9. Use mongod --version to check its succesfully installed

Build from Source*