MongoDB

Install MongoDB on Windows with WSL Ubuntu

  • dani

dani

4 min read

In this article, we will install a local MongoDB 6 database on Windows using a WSL Ubuntu subsystem. MongoDB is a document-based database, often referred to as NoSQL database.

If you do not know what WSL is and you want to learn how to set it up, go to my previous article:

Install Linux on Windows with WSL
Install Linux distribution (e.g. Ubuntu) on your Windows computer using Windows Subsystems for Linux (WSL).

The official WSL documentation has a tutorial on how to install MongoDB but is referring to MongoDB 5. We will instead go forward with MongoDB 6.

Installing MongoDB 6

First, open a new Terminal window and get the public key used by MongoDB package management:

wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -

Create a list file for MongoDB:

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

Yes, the spaces in the URL between the double-quotes are fine. Now the file /etc/apt/sources.list.d/mongodb-org-6.0.list should exist and if it is setup correct we can reload the local package database of Aptitude:

sudo apt-get update

This should now list the MongoDB repository along the standard Canonical repositories:

...
Get:5 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 Release [4412 B]
...

Install the MongoDB packages from the repository:

sudo apt-get install -y mongodb-org

After the command finishes, confirm the installation and get the version number:

mongod --version

This should print something like the following:

daniel@DESKTOP:~$ mongod --version
db version v6.0.2
Build Info: {
    "version": "6.0.2",
    "gitVersion": "94fb7dfc8b974f1f5343e7ea394d0d9deedba50e",
    "openSSLVersion": "OpenSSL 1.1.1f  31 Mar 2020",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "ubuntu2004",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

Make a new directory to store the data:

mkdir -p ~/data/db

Run the MongoDB instance:

sudo mongod --dbpath ~/data/db

Note, that this will block the current shell until you cancel MongoDB with the key combination CTRL + C, or you type exit. Typically you want the database to run in background. One drawback of WSL is that systemd is not available. So we need to setup an init script.

Setup an init script

To setup an init script to run MongoDB as a service, we will use the script from the MongoDB GitHub repository. We download the script and save it in /etc/init.d/:

curl https://raw.githubusercontent.com/mongodb/mongo/master/debian/init.d | sudo tee /etc/init.d/mongodb >/dev/null

Make the script executable by setting the permission flag:

sudo chmod +x /etc/init.d/mongodb

Now you can use the following command to start and stop MongoDB:

  • sudo service mongodb status for checking the status of your database. You should see a fail response if no MongoDB database is running.
  • sudo service mongodb start to start the MongoDB database. You should see the response * Starting database mongod [ OK ] in case the database was started successfully.
  • sudo service mongodb stop to stop the MongoDB database. You should see the response * Stopping database mongod [ OK ] in case the database was stopped successfully.

Note that the service will not use the directory ~/data/db to store the data we created before, because we do not pass the runtime argument anymore. To do that, you would need to adapt the config file in /etc/mongod.conf. The default location for storage is /var/lib/mongodb/.

Connect to and test the database

Check that the database is running by connecting to the database with the command:

mongosh

If it says MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017 then MongoDB is not running as expected. Otherwise you are connected and can create a new user mytestuser for the database mytestdatabase with the following commands:

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

This will ask you for the password once and then create the user with the chosen password. Afterwards, type exit to quit the MongoDB shell. We will login with the user we just created:

mongosh -u mytestuser -p --authenticationDatabase mytestdatabase

This will ask you for the password you just entered a minute ago. Enter the password to connect to the database. Next, we will use our database mytestdatabase again and use an example from the MongoDB documentation for insertion to create a new collection and insert data. Note that there are no tables as in SQL databases, so you do not need to create a table with a schema. Insert an example movie:

db.movies.insertOne(
  {
    title: "The Favourite",
    genres: [ "Drama", "History" ],
    runtime: 121,
    rated: "R",
    year: 2018,
    directors: [ "Yorgos Lanthimos" ],
    cast: [ "Olivia Colman", "Emma Stone", "Rachel Weisz" ],
    type: "movie"
  }
)

This will answer with something like:

{
  acknowledged: true,
  insertedId: ObjectId("63409e40c9164c75dedfb6d0")
}

It tells us the object has been created and gives us the object identifier. Type show collections to see that the movies collection has been created:

mytestdatabase> show collections
movies

We can read the specific movie we inserted from the collection:

mytestdatabase> db.movies.find( { title: "The Favourite" } )
[
  {
    _id: ObjectId("63409e40c9164c75dedfb6d0"),
    title: 'The Favourite',
    genres: [ 'Drama', 'History' ],
    runtime: 121,
    rated: 'R',
    year: 2018,
    directors: [ 'Yorgos Lanthimos' ],
    cast: [ 'Olivia Colman', 'Emma Stone', 'Rachel Weisz' ],
    type: 'movie'
  }
]

That's it! Our MongoDB works and is now ready to be used for development.