How to Install MongoDB on Debian 10 Buster

How to Install MongoDB on Debian 10 Buster

In this MongoDB tutorial, we will explain how to install and configure the latest version of MongoDB on Debian 10 Buster. Learn how to Install MongoDB on Debian 10 Linux. Learn how To Install MongoDB 4 on Debian 10 (Buster)

MongoDB is a free and open-source document database. It belongs to a family of databases called NoSQL, which is different from the traditional table-based SQL databases like MySQL and PostgreSQL.

In MongoDB, data is stored in flexible, JSON-like documents where fields can vary from document to document. It does not require a predefined schema, and data structure can be changed over time.

In this tutorial, we will explain how to install and configure the latest version of MongoDB Community Edition on Debian 10 Buster.

Installing MongoDB

MongoDB is not available in the standard Debian Buster repositories. We'll enable the official MongoDB repository and install the packages.

At the time of writing this article, the latest version of MongoDB is version 4.2. Before starting with the installation, head over to the Install on Debian page of MongoDB’s documentation and check if there is a new version available.

Perform the following steps as root or user with sudo privileges to install MongoDB on a Debian system:

  1. Install the packages required for adding a new repository:

    sudo apt install dirmngr gnupg apt-transport-https software-properties-common ca-certificates curl
  2. Add the MongoDB GPG key to your system:

    curl -fsSL | sudo apt-key add -
  3. Enable the MongoDB repository:

    sudo add-apt-repository 'deb buster/mongodb-org/4.2 main'

Packages with older versions of MongoDB are not available for Debian 10.

  1. Update the packages list and install the mongodb-org meta-package:

    sudo apt update
    sudo apt install mongodb-org

The following packages will be installed on the system as a part of the mongodb-org package:

  • mongodb-org-server - The mongod daemon and corresponding init scripts and configurations.
  • mongodb-org-mongos - The mongos daemon.
  • mongodb-org-shell - The mongo shell is an interactive JavaScript interface to MongoDB. It is used to perform administrative tasks through the command line.
  • mongodb-org-tools - Contains several MongoDB tools for importing and exporting data, statistics, as well as other utilities.
  1. Start the MongoDB service and enable it to start on boot:

    sudo systemctl enable mongod --now
  2. To verify whether the installation has completed successfully, connect to the MongoDB database server using the mongo tool and print the connection status:

    mongo --eval 'db.runCommand({ connectionStatus: 1 })'

The output will look like this:

MongoDB shell version v4.2.1
connecting to: mongodb://
Implicit session: session { "id" : UUID("09f11c53-605f-44ad-abec-ec5801bb6b06") }
MongoDB server version: 4.2.1
	"authInfo" : {
		"authenticatedUsers" : [ ],
		"authenticatedUserRoles" : [ ]
	"ok" : 1

A value of 1 for the ok field indicates success.

Configuring MongoDB

The MongoDB configuration file is named mongod.conf and is located in the /etc directory. The file is in YAML format.

The default configuration settings are sufficient for most users. However, for production environments, it is recommended to uncomment the security section and enable authorization, as shown below:

  authorization: enabled

The authorization option enables Role-Based Access Control (RBAC) that regulates users access to database resources and operations. If this option is disabled, each user can access all databases and perform any action.

After editing the configuration file, restart the mongod service for changes to take effect:

sudo systemctl restart mongod

To find more information about the configuration options available in MongoDB 4.2, visit the Configuration File Options documentation page.

Creating Administrative MongoDB User

If you enabled the MongoDB authentication, you'll need to create an administrative user that can access and manage the MongoDB instance. To do so, access the mongo shell with:


From inside the MongoDB shell, type the following command to connect to the admin database:

use admin

switched to db admin

Issue the following command to create a new user named mongoAdmin with the userAdminAnyDatabase role:

    user: "mongoAdmin", 
    pwd: "changeMe", 
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]

Successfully added user: {
	"user" : "mongoAdmin",
	"roles" : [
			"role" : "userAdminAnyDatabase",
			"db" : "admin"

You can name the administrative MongoDB user as you want.

Exit the mongo shell with:


To test the changes, access the mongo shell using the administrative user you have previously created:

mongo -u mongoAdmin -p --authenticationDatabase admin

Enter the password when prompted. Once you are inside the MongoDB shell connect to the admin database:

use admin

switched to db admin

Now, print the users with:

show users

	"_id" : "admin.mongoAdmin",
	"userId" : UUID("cdc81e0f-db58-4ec3-a6b8-829ad0c31f5c"),
	"user" : "mongoAdmin",
	"db" : "admin",
	"roles" : [
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
	"mechanisms" : [


We have shown you how to install MongoDB 4.2 on Debian 10, Buster. Visit the MongoDB Manual for more information on this topic.

If you hit a problem or have feedback, leave a comment below.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

How to connect to MongoDB database from Node.js?

How to connect to MongoDB database from Node.js?

Use Node.js? Want to learn MongoDB? In today’s post, we’ll work through connecting to a MongoDB database from a Node.js script, retrieving a list of databases, and printing the results to your console.

In today’s post, we’ll work through connecting to a MongoDB database from a Node.js script, retrieving a list of databases, and printing the results to your console.

Set up

Before we begin, we need to ensure you’ve completed a few prerequisite steps.

Install Node.js

First, make sure you have a supported version of Node.js installed (the MongoDB Node.js Driver requires Node 4.x or greater and for these examples, I've used Node.js 10.16.3).

Install the MongoDB Node.js Driver

The MongoDB Node.js Driver allows you to easily interact with MongoDB databases from within Node.js applications. You’ll need the driver in order to connect to your database and execute the queries described in this Quick Start series.

If you don’t have the MongoDB Node.js Driver installed, you can install it with the following command.

npm install mongodb

At the time of writing, this installed version 3.3.2 of the driver. Running npm list mongodb will display the currently installed driver version number. For more details on the driver and installation, see the official documentation.

Create a free MongoDB Atlas cluster and load the sample data

Next, you’ll need a MongoDB database. Your database will be stored inside of a cluster. At a high level, a cluster is a set of nodes where copies of your database will be stored.

The easiest way to get started with MongoDB is to use Atlas, MongoDB’s fully-managed database-as-a-service. Head over to Atlas and create a new cluster in the free tier. Once your tier is created, load the sample data.

Get started with an M0 cluster on Atlas today. It's free forever, and it’s the easiest way to try out the steps in this blog series.

If you’re not familiar with how to create a new cluster and load the sample data, check out this video tutorial from MongoDB Developer Advocate Maxime Beugnet.

Get your cluster’s connection info

The final step is to prep your cluster for connection.

In Atlas, navigate to your cluster and click CONNECT. The Cluster Connection Wizard will appear.

The Wizard will prompt you to whitelist your current IP address and create a MongoDB user if you haven’t already done so. Be sure to note the username and password you use for the new MongoDB user as you’ll need them in a later step.

Next, the Wizard will prompt you to choose a connection method. Select Connect Your Application. When the Wizard prompts you to select your driver version, select Node.js and 3.0 or later. Copy the provided connection string.

For more details on how to access the Connection Wizard and complete the steps described above, see the official documentation.

Connect to your database from a Node.js application

Now that everything is set up, it’s time to code! Let’s write a Node.js script that connects to your database and lists the databases in your cluster.

Import MongoClient

The MongoDB module exports MongoClient, and that’s what we’ll use to connect to a MongoDB database. We can use an instance of MongoClient to connect to a cluster, access the database in that cluster, and close the connection to that cluster.

const {MongoClient} = require('mongodb');

Create our main function

Let’s create an asynchronous function named main() where we will connect to our MongoDB cluster, call functions that query our database, and disconnect from our cluster.

The first thing we need to do inside of main() is create a constant for our connection URI. The connection URI is the connection string you copied in Atlas in the previous section. When you paste the connection string, don’t forget to update <username> and <password> to be the credentials for the user you created in the previous section. Note: the username and password you provide in the connection string are NOT the same as your Atlas credentials.

 * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
 * See for more details
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";

Now that we have our URI, we can create an instance of MongoClient.

const client = new MongoClient(uri);

Note: When you run this code, you may see DeprecationWarnings around the URL string parser and the Server Discover and Monitoring engine. If you see these warnings, you can remove them by passing options to the MongoClient. For example, you could instantiate MongoClient by calling new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }). See the Node.js MongoDB Driver API documentation for more information on these options.

Now we’re ready to use MongoClient to connect to our cluster. client.connect() will return a promise. We will use the await keyword when we call client.connect() to indicate that we should block further execution until that operation has completed.

await client.connect();

Now we are ready to interact with our database. Let’s build a function that prints the names of the databases in this cluster. It’s often useful to contain this logic in well named functions in order to improve the readability of your codebase. Throughout this series, we’ll create new functions similar to the function we’re creating here as we learn how to write different types of queries. For now, let’s call a function named listDatabases().

await listDatabases(client);

Let’s wrap our calls to functions that interact with the database in a try/catch statement so that we handle any unexpected errors.

try {
    await client.connect();

    await listDatabases(client);

} catch (e) {

We want to be sure we close the connection to our cluster, so we’ll end our try/catch with a finally statement.

finally {
    await client.close();

Once we have our main() function written, we need to call it. Let’s send the errors to the console.


Putting it all together, our main() function and our call to it will look something like the following.

async function main(){
     * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
     * See for more details
    const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";

    const client = new MongoClient(uri);

    try {
        // Connect to the MongoDB cluster
        await client.connect();

        // Make the appropriate DB calls
        await  listDatabases(client);

    } catch (e) {
    } finally {
        await client.close();


List the databases in our cluster

In the previous section, we referenced the listDatabases() function. Let’s implement it!

This function will retrieve a list of databases in our cluster and print the results in the console.

async function listDatabases(client){
    databasesList = await client.db().admin().listDatabases();

    databasesList.databases.forEach(db => console.log(` - ${}`));

Save Your File

You’ve been implementing a lot of code. Save your changes, and name your file something like connection.js. To see a copy of the complete file, visit the nodejs-quickstart GitHub repo.

Execute Your Node.js Script

Now you’re ready to test your code! Execute your script by running a command like the following in your terminal: node connection.js

You will see output like the following:

 - sample_airbnb
 - sample_geospatial
 - sample_mflix
 - sample_supplies
 - sample_training
 - sample_weatherdata
 - admin
 - local

What’s next?

Today, you were able to connect to a MongoDB database from a Node.js script, retrieve a list of databases in your cluster, and view the results in your console. Nice!

In future posts in this series, we’ll dive into each of the CRUD (create, read, update, and delete) operations as well as topics like change streams, transactions, and the aggregation pipeline, so you’ll have the tools you need to successfully interact with data in your databases.

In the meantime, check out the following resources:

Series versions

This examples in this article were created with the following application versions:

MongoDB: 4.0
MongoDB Node.js Driver: 3.3.2
Node.js: 10.16.3

MongoDB Tutorial - How to backup and restore a database

MongoDB Tutorial - How to backup and restore a database

This is a quick example to show how to easily backup and restore a MongoDB database from the command line, using the current date as the backup folder name (YYYYMMDD)

Originally published at
Backup MongoDB database using date for the folder name

The mongodump command will create a backup / dump of the MongoDB database with the name specified by the --db [DB NAME] argument.

The --out /var/backups/`date +"%Y%m%d" argument specifies the output directory as /var/backups/[TODAY'S DATE] e.g. /var/backups/20190903.

sudo mongodump --db [DB NAME] --out /var/backups/`date +"%Y%m%d"`
Restore MongoDB database from backup

The mongorestore command restores a database to the destination --db [DB NAME] from the specified directory, e.g. /var/backups/20190903.

sudo mongorestore --db [DB NAME] /var/backups/[BACKUP FOLDER NAME]

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

MongoDB - The Complete Developer’s Guide

The Complete Developers Guide to MongoDB

Learn MongoDB : Leading NoSQL Database from scratch

Learn NoSQL Databases - Complete MongoDB Bootcamp 2019

MongoDB Connection Initialization – Node.js API with TDD Tutorial

Building a simple app using NodeJS, MongoDB, and ExpressJS

Node, Express, React.js, Graphql and MongoDB CRUD Web Application

Building REST API with Nodejs / MongoDB /Passport /JWT

Auto-Scaling with MongoDB Atlas, the Fully Managed Cloud Database

Auto-Scaling with MongoDB Atlas, the Fully Managed Cloud Database

Learn about storage and compute auto-scaling, just some of the MongoDB Atlas features that help you automate capacity management. Auto-Scaling with MongoDB Atlas, the Fully Managed Cloud Database

Learn about storage and compute auto-scaling, just some of the MongoDB Atlas features that help you automate capacity management.