MongoDB is an open-source, cross-platform, distributed NoSQL (Non-SQL or Non-Relational) database system. MongoDB uses flexible documents to store various data forms instead of storing data in tables like traditional SQL databases. MongoDB uses BSON format for storing data, which is binary JSON format.

MongoDB is a distributed NoSQL database with built-in high availability, automatic failover and data redundancy, and horizontal scaling via sharding across distributed clusters, and it supports multi-region geographic deployment. MongoDB also provides query API that supports CRUD operations (read and write), data aggregation pipeline, text search, and geospatial queries.

Some notable companies that use MongoDB are Forbes, Toyota, SEGA, EA, Vodafone, Verizon, and many more.

In this guide, you will install MongoDB NoSQL Database on a Debian 11 server. You’ll also optimize your Debian server for the MongoDB deployment. At the end of this guide, you’ll also learn some of MongoDB operations, the basic CRUD (Create, Read, Update, and Delete) in MongoDB.

By completing this guide, you’ll have MongoDB installed and running on an optimized Linux server. Also, you’ll understand and know some basic MongoDB operations, including creating users and databases, inserting and retrieving data, updating data, and deleting data in MongoDB.

Prerequisites

To complete this guide, you must have the following requirements:

  • A Debian 11 or Debian 12 server – this example uses a Debian server with the hostname ‘mongodb-server’.
  • A non-root user with sudo/root privileges.

With all prerequisites ready, you’re now ready to start MongoDB installation.

Adding MongoDB Repository

To install MongoDB, you must add the official MongoDB repository to your system. And at the time of this writing, the latest version of MongoDB is v6.0. In this first step, you’ll add the MongoDB repository to your Debian 11 system.

Before you get started, run the below apt command to update and refresh your package index. Then, install some basic dependneices such as gnupg2 and apt-transport-https.

sudo apt update
sudo apt install gnupg2 apt-transport-https wget curl

When prompted, input y to confirm and press ENTER.

How to Install and Use MongoDB on Debian Debian linux

After the dependencies are installed, run the below command to download and add the GPG key for the MongoDB repository. This will automatically convert the GPG key ‘server-6.0.asc‘ to ‘/usr/share/keyrings/mongodb-org-6.0.gpg‘.

wget -q -O- https://www.mongodb.org/static/pgp/server-6.0.asc | 
    gpg --dearmor | sudo tee /usr/share/keyrings/mongodb-org-6.0.gpg > /dev/null 2>&1

Now run the below command to add the MongoDB repository for the MongoDB v6.0.

On Debian 11

echo "deb [signed-by=/usr/share/keyrings/mongodb-org-6.0.gpg] http://repo.mongodb.org/apt/debian bullseye/mongodb-org/6.0 main" | 
    sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

How to Install and Use MongoDB on Debian Debian linux

On Debian 12

echo "deb [signed-by=/usr/share/keyrings/mongodb-org-6.0.gpg] http://repo.mongodb.org/apt/debian bookworm/mongodb-org/6.0 main" | 
    sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

For Debian 11 and 12

Lastly, update and refresh your package index via the apt command below. This will retrieve new metadata for the MongoDB repository.

sudo apt update

You should receive an output like this:

How to Install and Use MongoDB on Debian Debian linux

You’ll next start the MongoDB installation with the MongoDB repository added to your Debian system.

Installing MongoDB Server and Mongosh

In this step, you’ll install the MongoDB server package and mongosh as the MongoDB client to your Debian server. You’ll install the latest version of the MongoDB server and Mongosh v6.0.

Run the below apt command to install the ‘mongodb-org‘ and ‘mongodb-mongosh‘ packages.

sudo apt install mongodb-org mongodb-mongosh

Input y when prompted and press ENTER to proceed.

How to Install and Use MongoDB on Debian Debian linux

After MongoDB is installed, run the below systemctl command utility to start and enable the MongoDB service.

sudo systemctl start mongod
sudo systemctl enable mongod

Now verify the MongoDB service via the following command. You should see that the MongoDB service is enabled and will be run automatically upon the bootup. And the status of the MongoDB service is running.

sudo systemctl status mongod

How to Install and Use MongoDB on Debian Debian linux

Now, you’ve installed the MongoDB server on a Debian 11 server. In the next step, you’ll set up and optimize your Debian server for MongoDB deployment.

Setting up System

You’ll optimize your Debian server for the MongoDB installation in this step. First, you’ll disable Transparent Huge Pages (THP) on your system via the systemd service file, then increase the ulimit and max virtual memory.

First, you’ll disable Transparent Huge Pages (THP). To do that, create a new systemd service file ‘/etc/systemd/system/disable-thp.service‘ using the below nano editor command.

sudo nano /etc/systemd/system/disable-thp.service

Add the following lines to the file. This service will disable THP by replacing the content of files ‘/sys/kernel/mm/transparent_hugepage/enabled‘ and ‘/sys/kernel/mm/transparent_hugepage/defrag‘ to ‘never‘.

[Unit]
Description=Disable Transparent Huge Pages (THP)
[Service]
Type=simple
ExecStart=/bin/sh -c "echo 'never' > /sys/kernel/mm/transparent_hugepage/enabled && echo 'never' > /sys/kernel/mm/transparent_hugepage/defrag"

[Install]
WantedBy=multi-user.target

Save the file and exit the editor when finished.

Now run the below systemctl command to reload the systemd manager and apply the changes.

sudo systemctl daemon-reload

After that, start and enable the service ‘disable-thp’ via the below systemctl command utility. With this, you’ll now have THP disabled on every boot up.

sudo systemctl enable disable-thp
sudo systemctl start disable-thp

After disabling THP, you’ll need to increase the ulimit for the MongoDB server.

How to Install and Use MongoDB on Debian Debian linux

The default ulimit on Linux system is ‘1024‘, while the MongoDB server required at least ulimit ‘64000‘. You’ll now increase the ulimit for specific MongoDB user via the system limits config file.

Create a new config file ‘/etc/security/limits.d/mongodb.conf’ using the below nano editor command.

sudo nano /etc/security/limits.d/mongodb.conf

Add the following lines to the file. With this, you’ll increase ulimit for specific MongoDB user ‘mongod‘.

mongod soft nproc 64000
mongod hard nproc 64000
mongod soft nofile 64000
mongod hard nofile 64000

Save and exit the editor when you’re done.

With the ulimit now configured, you’ll now increase the max virtual memory on your Debian server via the ‘/etc/sysctl.conf‘ file.

Open the file ‘/etc/sysctl.conf‘ using the below nano editor command.

sudo nano /etc/sysctl.conf

Add the following lines to the end of the line.

fs.file-max = 2097152
vm.max_map_count = 262144
vm.swappiness = 1

Save the file and exit the editor when finished.

How to Install and Use MongoDB on Debian Debian linux

Lastly, run the below command to reboot your MongoDB server and apply the system changes that you have made.

sudo reboot

Now your Debian server will be running with THP disabled, the ulimit for the ‘mongod’ user increased, and the max virtual memory also increased. In the next step, you’ll learn how to secure MongoDB by creating an admin user and enabling authentication and authorization.

Setting up Admin MongoDB

In this step, you’ll learn how to create a new user in MongoDB via the ‘mongosh’ MongoDB client. Then, you’ll also enable authentication and authorization on your MongoDB server via the ‘/etc/mongod.conf’ file.

Log in to the MongoDB shell via the ‘mongosh’ command below.

mongosh

After logging in, you should be connected to the default database ‘test‘.

Now run the below query to disable the free monitoring on your MongoDB server.

db.disableFreeMonitoring()

How to Install and Use MongoDB on Debian Debian linux

Next, show to the database ‘admin’ and create a new MongoDB admin user ‘myAdminUser’ using the following MongoDB queries. You’ll also be prompted to set up a password for your new user.

use admin
db.createUser(
  {
    user: "myAdminUser",
    pwd: passwordPrompt(),
    roles: [
      { role: "userAdminAnyDatabase", db: "admin" },
      { role: "readWriteAnyDatabase", db: "admin" }
    ]
  }
)

When the new user and password are created, you’ll see an output such as ‘{ ok: 1 }‘ on your terminal screen. This means that you’ve successfully created a new user.

How to Install and Use MongoDB on Debian Debian linux

Now press Ctrl d or type quit to exit from the MongoDB shell.

After creating a new admin user for MongoDB, you’ll then enable authentication and authorization on your MongoDB server.

Run the below nano editor command to open the MongoDB config file ‘/etc/mongod.conf‘.

sudo nano /etc/mongod.conf

Uncomment the ‘security‘ parameter and add the option ‘authorization: enabled‘ as the below lines.

security:
    authorization: enabled

Save the file and exit the editor.

Lastly, run the below systemctl command utility to restart the MongoDB service and apply the changes.

sudo systemctl restart mongod

With this, you’ve now created an admin user for the MongoDB server ‘myAdminuser’ and created the password. Also, you’ve enabled the authentication and authorization on your MongoDB server via the config file ‘/etc/mongod.conf’. In the next step, you’ll verify your MongoDB admin user and verify the authentication to ensure that you’ve secured your MongoDB deployment.

Verifying MongoDB Admin User

In this step, you’ll verify the new MongoDB admin user by logging in to the MongoDB server via the mongosh command and verify the authentication using the new admin user.

Run the below command to log in to the MongoDB shell.

mongosh

Now run the below query to authenticate using the new MongoDB admin user ‘myAdminUser‘. When prompted, input your MongoDB admin user.

use admin
db.auth("myAdminUser", passwordPrompt())

When successful, you should receive an output such as ‘{ ok: 1 }‘.

How to Install and Use MongoDB on Debian Debian linux

You can also connect to MongoDB and authenticate at the same time with a one-line command. Run the below ‘mongosh‘ command to connect to the MongoDB server that running by default on port 27017 via the admin user ‘myAdminUser‘.

mongosh --port 27017 --authenticationDatabase 
    "admin" -u "myAdminUser" -p

When prompted for the password, input your MongoDB admin and you should now be logged in to the MongoDB shell.

Now run the below query to verify the current connection to the MongoDB server.

db.runCommand({connectionStatus : 1})

You should receive an output similar to this – You’re connected to the MongoDB server and authenticated as the admin user ‘myAdminUser‘.

How to Install and Use MongoDB on Debian Debian linux

Creating User and Database on MongoDB

In this step, you’ll learn how to create a new MongoDB user that can be used for your application. You’ll create a new MongoDB user with access (read or write) to the specific database. You’ll also verify the new MongoDB user by logging in to the MongoDB shell and verifying the detailed connection.

Before you start, ensure that you’ve logged in to the MongoDB server. Then, switch to the database ‘testdb‘ using the below query.

use tesdb

Now run the below query to create a new MongoDB user. In this example, you’ll create a new user ‘MyTestUser‘ with the role ‘readWrite‘ to the database ‘testdb‘ and role ‘read‘ to the database ‘reporting‘.

db.createUser(
  {
    user: "myTestUser",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "testdb" },
             { role: "read", db: "reporting" } ]
  }
)

When prompted, input the password for your new user. Then you’ll receive an output such as ‘{ ok: 1 }’, which means the new user is created.

How to Install and Use MongoDB on Debian Debian linux

After creating a new MongoDB user, you’ll now verify the list of the user on MongoDB.

Run the below query to switch to the database ‘admin‘. Then, verify the list of the user on your MongoDB server.

use admin
db.system.users.find()

You should receive an output like this – The new user ‘myTestUser‘ is created.

How to Install and Use MongoDB on Debian Debian linux

Press Ctrl d or type quit to exit/log out from the MongoDB shell.

Lastly, run the below mongosh command to log in to MongoDB via the new user ‘myTestUser‘. Input the password for your user.

mongosh --port 27017 -u "myTestUser" 
    --authenticationDatabase "testdb" -p

After logging in, run the below query to verify the status of your current connection.

db.runCommand({connectionStatus : 1})

You should receive an output similar to this – with this, you’ve now logged in to the MongoDB server and authorized as the new user ‘myTestUser‘.

How to Install and Use MongoDB on Debian Debian linux

With this, you’ve now created a new MongoDB user ‘myTestUser‘ that can be used for your application deployment. This user also has privileges/roles for ‘readWrite‘ to the database ‘testdb‘ and the ‘read‘-only role to the database ‘reporting‘.

In the next step, you’ll learn the basic operation of MongoDB, which includes inert and retrieving data, updating data, and deleting data from the MongoDB server.

Inserting and Querying Data

After creating a new MongoDB user, you’ll now learn how to create the database,  insert data, and retrieve data from MongoDB. You’ll learn how to use the ‘insertOne’ query and ‘insertMany’ query to add data to MongoDB, and learn how to use query operators such as ‘$in’ and ‘$gte’.

First, switch to the database ‘testdb‘ using the following query.

use testdb

Run the below query to insert new data and create a new collection to the database ‘testdb‘. In this example, you’ll create a new collection ‘movies‘ to the database ‘testdb‘, and you’ll use the ‘inertOne‘ query to insert new data.

The ‘insertOne‘ query is used to add a new one/single data to the MongoDB collection.

db.movies.insertOne(
  {
    title: "The Hobbit",
    genres: [ "Adventure", "Fantasy" ],
    runtime: 172,
    rated: "R",
    year: 2012,
    directors: [ "Peter Jackson" ],
    cast: [ "Martin Freeman", "Ian McKellen", "Richard Armitage" ],
    type: "movie"
  }
)

You’ll now receive an output such as ‘acknowledged: ok‘, which means the new data added and the new collection is created.

How to Install and Use MongoDB on Debian Debian linux

Now run the below query to verify the list of collections on the database ‘testdb‘ and show available data within the ‘testdb‘.

The ‘show collection‘ query will show you the lists of collections/tables on the current database, and the ‘find‘ query will show available data on your database. You can also filter specific fields via the ‘find’ query.

show collections
db.movies.find( { title: "The Hobbit" } )

You should receive an output like this – The collection ‘movies‘ is available in the ‘testdb‘ database. Also, you’ll the new data that you’ve added, which is

How to Install and Use MongoDB on Debian Debian linux

Next, you can also add multiple data at once via the ‘insertMany‘ query. Run the below query to insert two data to the ‘movies‘ collection via the ‘insertMany‘ query.

db.movies.insertMany([
   {
      title: "The Lord of the Rings",
      genres: [ "Action", "Adventure", "Drama" ],
      runtime: 240,
      rated: "PG-13",
      year: 2001,
      directors: [ "Peter Jackson" ],
      cast: [ "Elijah Wood", "Ian McKellen", "Orlando Bloom" ],
      type: "movie"
    },
    {
      title: "Harry Potter",
      genres: [ "Adventure", "Family", "Fantasy" ],
      runtime: 140,
      rated: "R",
      year: 2007,
      directors: [ "David Yates" ],
      cast: [ "Daniel Radcliffe", "Emma Watson", "Rupert Grint" ],
      type: "movie"
    },
    {
    title: "Transformers",
    genres: [ "Adventure", "Action", "Sci-Fi" ],
    runtime: 150,
    rated: "PG-13",
    year: 2007,
    directors: [ "Michael Bay" ],
    cast: [ "Shia LaBeouf", "Megan Fox", "Josh Duhamel" ],
    type: "movie"
    }
])

Output:

How to Install and Use MongoDB on Debian Debian linux

Now run the below ‘find‘ query to retrieve your data. With this, you’ll retrieve data with the filter ‘directors: “Peter Jackson”‘.

db.movies.find( { directors: "Peter Jackson" })

You’ll receive an output like this – Any movies with ‘directors: “Peter Jackson”‘ will be shown on your terminal.

How to Install and Use MongoDB on Debian Debian linux

Next, you can also specify conditions in the ‘find’ query using query operators.

Run the below query to retrieve any data where the ‘genres‘ is ‘Action‘, ‘Family‘, and/or ‘Sci-Fi‘. The ‘$in‘ operator can be used to retrieve data that matches any of the values specified in an array.

db.movies.find( { genres: { $in: [ "Action", "Family", "Sci-Fi" ] } } )

How to Install and Use MongoDB on Debian Debian linux

Another query operator that you can try is ‘$gte’, which can be used to retrieve data that are greater than or equal to a specified value.

run the below query to retrieve data with the ‘$gte‘ query operator. This will retrieve any movies with ‘genres: “Adventure“‘ with a runtime greater or equal to ‘150‘.

db.movies.find( { genres: "Adventure", "runtime": { $gte: 150 } } )

You will receive an output similar to this – In this example, you’ll get three movies with runtimes more or equal to ‘150‘ with the genres ‘Adventure‘.

How to Install and Use MongoDB on Debian Debian linux

With this in mind, you’ve now learned how to insert and retrieve data in MongoDB. You’ve learned the basic query ‘insertOne‘ for adding one data and the ‘insertMany‘ query for adding some data at once.

Then, you’ve also learned the basic usage of the ‘find‘ query to retrieve data from MongoDB. In addition to that, you’ve also learned how to use operator queries ‘$in‘ and ‘$gte‘ in MongoDB.

In the next step, you’ll learn how to update data in MongoDB collections.

Updating Data in MongoDB

In this step, you’ll learn how to update data in MongoDB using two queries, the ‘updateOne‘ for updating one field inside the document and using the ‘replaceOne‘ to replace entirely first matched data with new data.

To update data in MongoDB, you can use multiple methods and queries. In this example, you’ll learn how to use the ‘updateOne‘ and ‘replaceOne‘ queries. The ‘updateOne‘ query can be used to update a single field in the document, while the ‘replaceOne‘ will replace the entire document.

Run the below query to update data using the ‘updateOne‘ query. In this example, you’ll update the ‘rated: “PG-13“‘ to ‘rated: “R“‘ on the movie ‘Transformers‘.

db.movies.updateOne( { title: "Transformers" },
{
  $set: {
    rated: "R"
  }
})

You should receive an output such as ‘matchedCount: 1‘ and ‘modifiedCount: 1‘.

How to Install and Use MongoDB on Debian Debian linux

Now verify the new data with the following query. You should see the data on the ‘Transformers‘ movie is updated.

db.movies.find( { title: "Transformers" })

How to Install and Use MongoDB on Debian Debian linux

Next, run the below ‘replaceOne‘ query to replace the first matched data in the filter and replace the entire document with the new data. In this example, you’ll replace the whole document on the movie ‘Transformers‘ with the new data.

db.movies.replaceOne(
  { title: "Transformers" },
  {
    title: "Transformers: Dark of the Moon",
    genres: [ "Adventure", "Action", "Sci-Fi" ],
    runtime: 160,
    rated: "PG-13",
    year: 2011,
    directors: [ "Michael Bay" ],
    cast: [ "Shia LaBeouf", "Rosie Huntington-Whiteley", "Tyrese Gibson" ],
    type: "movie"
  }
)

You should now get an output like this.

How to Install and Use MongoDB on Debian Debian linux

Now run the below query to verify the newly updated data on your MongoDB.

db.movies.find( { title: "Transformers" })
db.movies.find( { title: "Transformers: Dark of the Moon" })

You should receive an output similar to this – The movie ‘Transformers‘ is removed/replaced with the new movie ‘Transformers: Dark of the Moon‘.

How to Install and Use MongoDB on Debian Debian linux

Delete Data in MongoDB

In this step, you will learn how to delete data in a MongoDB document. Then, you’ll learn how to delete the database and delete the user in MongoDB.

Run the below command to delete data from the MongoDB collection. In this example, you’ll delete the whole document ‘Transformers: Dark of the Moon‘ via the ‘deleteMany‘ query.

db.movies.deleteMany( { title: "Transformers: Dark of the Moon" } )
db.movies.find( { title: "Transformers: Dark of the Moon" })

You should receive an output such as ‘deletedCount: 1‘.

How to Install and Use MongoDB on Debian Debian linux

Next, run the below command to delete a single document via the ‘deleteOne‘ query below. This will delete the first matched data within the filter.

In this example, you’ll delete the first document that matched with ‘cast: “Ian McKellen”‘.

db.movies.deleteOne( { cast: "Ian McKellen" } )
db.movies.find( { cast: "Ian McKellen" })

Below is the output before and after the data is deleted.

Before the remove – You should see two movies with the ‘cast: “Ian McKellen”‘.

How to Install and Use MongoDB on Debian Debian linux

After the document is removed – you should see only one movie with ‘cast: “Ian McKellen”‘.

How to Install and Use MongoDB on Debian Debian linux

Next, you’ll learn how to delete users and databases in MongoDB. To delete the user in MongoDB, you must have the role ‘root‘ on your MongoDB admin user.

Run the below command to authenticate as MongoDB admin user ‘myAliceAdmin‘ and input your password.

use admin
db.auth("myAdminUser", passwordPrompt())

After authentication, run the below query to give the admin user the ‘root’ roles.

db.grantRolesToUser("myAdminUser", ["root"]);

How to Install and Use MongoDB on Debian Debian linux

Now switch to the ‘testdb‘ and delete users within the database ‘testdb‘ via the below query. This will delete the user ‘myTestUser‘ from MongoDB.

use testdb
db.runCommand( { dropAllUsersFromDatabase: 1 } )

You should get an output such as ‘{ n:1, ok: 1 }‘.

Next, run the below query to delete/remove the database ‘testdb’.

db.dropDatabase()

And you should get an output such as ‘{ ok: 1, dropped: ‘testdb’ }‘.

How to Install and Use MongoDB on Debian Debian linux

Now that the ‘testdb’ and users within the database are removed.

Run the below query to switch to the database ‘admin‘ and verify the list of databases on your MongoDB server. You should see that the ‘testdb‘ database is removed.

use admin
show dbs

How to Install and Use MongoDB on Debian Debian linux

Lastly, run the below query to show and list users on MongoDB.

db.system.users.find()

You should receive an output like this – The use ‘myTestUser‘ is removed/deleted from the MongoDB server.

How to Install and Use MongoDB on Debian Debian linux

Conclusion

In this guide, you’ve installed the latest version of MongoDB Server (Community Edition) on a Debian server. You’ve also learned how to enable authentication and authorization on the MongoDB server and how to optimize the Linux server for the MongoDB deployment.

Along the way, you’ve learned the basic usage of the Mongosh command for connecting and managing the MongoDB server. And learned the basic MongoDB queries for creating users, creating databases, inserting and retrieving data, updating data, and deleting/removing data from the MongoDB server.

With this, you can learn more about MongoDB queries in MongoDB Documentation. Also, if you’re interested in deploying MongoDB in a large deployment, you can try to enable sharding that allows you to set up horizontal scaling in the MongoDB cluster.