Introduction

MongoDB is an open-source NoSQL database management system that uses a document-oriented data model. This guide will help you install and secure MongoDB on a Windows VPS.

Prerequisites

  • A Windows VPS with administrative access.
  • Basic knowledge of the Windows command line.

Step 1: Download MongoDB

Go to the MongoDB Community Server download page.

Select your version, make sure “Windows” is selected as the operating system, and choose the MSI package. Click on “Download” to start the download.

Step 2: Install MongoDB

Once the download is complete, locate the MSI installer file and double-click to start the installation. Follow these steps:

  • Choose “Complete” when prompted for the installation type.
  • Ensure “Install MongoDB as a Service” is checked.
  • Select the “Run Service as Network Service user” for user account options.
  • Proceed with the installation by clicking “Next” until the installation completes.

Step 3: Create Data and Log Directories

By default, MongoDB stores data in the C:\data\db directory. You will need to create this directory:

mkdir C:\data
mkdir C:\data\db

You may also want a log directory:

mkdir C:\data\log

Step 4: Configure MongoDB (Optional)

You can modify the MongoDB configuration file located at C:\Program Files\MongoDB\Server\\bin\mongod.cfg if you need to change default settings like port or database path.

Step 5: Start MongoDB Service

Open the command prompt as an administrator, and use the following command to start the MongoDB service:

net start MongoDB

Step 6: Verify MongoDB Installation

To verify that MongoDB is running, you can check the status with:

sc query MongoDB

You can also connect to the MongoDB shell by running the following command:

mongo

Step 7: Secure MongoDB

By default, MongoDB does not enable access control. To secure your database, follow these steps:

7.1: Enable Authentication

Open the MongoDB configuration file, typically found at C:\Program Files\MongoDB\Server\\bin\mongod.cfg. Add the following lines to enable authorization:

security:
  authorization: "enabled"

Save the changes to the configuration file.

7.2: Create an Admin User

Restart the MongoDB service to apply the changes:

net stop MongoDB
net start MongoDB

Next, open the MongoDB shell:

mongo

In the shell, switch to the admin database and create an administrative user:

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

Make sure to replace your_secure_password with a strong password.

7.3: Exit the MongoDB Shell

exit

Step 8: Access MongoDB with Authentication

You can now connect to MongoDB using the newly created user:

mongo -u admin -p your_secure_password --authenticationDatabase admin

Conclusion

You have successfully installed and secured MongoDB on your Windows VPS. The setup includes creating an admin user and enabling authentication to secure your MongoDB instance.

Resources