Install MongoDB on Ubuntu VPS — NoSQL Database for Beginners

If you need a database that stores JSON-like documents, scales horizontally, and fits modern apps like Node.js, realtime services, or IoT — MongoDB is the most popular NoSQL database in the world, powering Discord, eBay, and Adobe.

This guide walks you through installing MongoDB Community Edition 7.0 on Ubuntu 22.04, from adding the official repository to enabling authentication, creating users, allowing remote connections, and backing up with mongodump.

Prerequisites: Ubuntu 22.04 VPS with at least 2 GB RAM (MongoDB uses more RAM than MySQL/PostgreSQL), sudo access, and SSH on port 22.

What is MongoDB — How Document Databases Work

MongoDB stores data as BSON (Binary JSON). Each record is a "Document," and Documents live in "Collections" (the NoSQL equivalent of SQL tables). Documents in the same Collection do not need the same structure — you can add fields on the fly without ALTER TABLE.

MongoDB vs MySQL — Which One?

TopicMongoDBMySQL
StructureDocument (BSON / JSON)Table (rows / columns)
SchemaFlexible — add fields instantlyFixed — needs ALTER TABLE
QueryJSON-like (find, aggregate)Standard SQL
TransactionsMulti-document since v4.0Full ACID with InnoDB
Best forRealtime apps, CMS, IoT, mobile backendsGeneric web, ERP, accounting

Step 1 — Add the MongoDB Official Repository

Ubuntu's default repo ships an older MongoDB; the official repo gives you v7.0. Start by importing the GPG key:

sudo apt update && sudo apt install -y gnupg curl
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
  sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor

Add the source list for MongoDB 7.0 on Ubuntu 22.04 (Jammy):

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \
  sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

Step 2 — Install and Start MongoDB

sudo apt update
sudo apt install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod

If the status reads active (running), the install succeeded. Open the shell:

mongosh

You should see a prompt like test>. List existing databases:

show dbs

Step 3 — Enable Authentication (Critical)

By default MongoDB ships without authentication. Enable it before going to production. Create an admin user first:

mongosh
use admin
db.createUser({
  user: "adminUser",
  pwd: "StrongAdminPassword!",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})
exit

Edit MongoDB's config:

sudo nano /etc/mongod.conf

Add (or modify) the security section:

security:
  authorization: enabled

Restart to apply:

sudo systemctl restart mongod

Log in again using the admin user:

mongosh -u adminUser -p --authenticationDatabase admin

Step 4 — Create a Database and App User

Never use the admin user from your app. Create a per-database user instead:

use myapp_db
db.createUser({
  user: "myapp",
  pwd: "AppPassword123!",
  roles: [ { role: "readWrite", db: "myapp_db" } ]
})

Test the login:

mongosh -u myapp -p --authenticationDatabase myapp_db myapp_db

Step 5 — Allow Remote Connections

By default MongoDB binds only to 127.0.0.1. To accept external clients edit bindIp in /etc/mongod.conf:

net:
  port: 27017
  bindIp: 0.0.0.0   # listen on every interface — pair with a firewall!

⚠️ Danger: bindIp: 0.0.0.0 exposes MongoDB to the entire internet. You MUST run a firewall and restrict source IPs, and you must have enabled authentication from Step 3 first.

Restrict access via UFW:

sudo ufw allow from YOUR_APP_IP to any port 27017

Step 6 — Back Up with mongodump

MongoDB ships mongodump for backups:

mongodump --uri="mongodb://myapp:[email protected]:27017/myapp_db" \
  --out=/backup/mongo_$(date +%F)

Restore from a backup:

mongorestore --uri="mongodb://myapp:[email protected]:27017/myapp_db" \
  --drop /backup/mongo_2026-05-15/myapp_db

Tip: Schedule mongodump nightly via cron and upload the result to S3 or Google Drive with rclone for off-host safety.

Tune MongoDB on Ubuntu VPS for Production

Once MongoDB is installed and authentication is enabled, several settings still deserve attention before real traffic hits your VPS — particularly WiredTiger cache, disk, swap, and logging. MongoDB consumes more RAM than a typical SQL database, so a misconfiguration can trigger an OOM (Out Of Memory) event where the kernel kills mongod mid-flight.

By default MongoDB sizes its WiredTiger cache at 50% of RAM minus 1 GB. On a small VPS that shares RAM with Nginx, PHP-FPM, or Node.js, you should cap the cache yourself so MongoDB does not starve the other services. Open /etc/mongod.conf and add this under the storage section:

storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 1.0   # cap cache at 1GB on a 2GB-RAM VPS

On low-RAM VPS instances, add swap to survive heavy queries and disable Transparent Huge Pages (THP), which MongoDB recommends turning off because it causes latency spikes:

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Tip: Check the RAM MongoDB actually uses with db.serverStatus().wiredTiger.cache in mongosh, or watch the whole system with htop. If the cache fills up constantly, consider upgrading your VPS RAM.

Create Indexes to Speed Up Queries

Just like SQL, a Collection with many Documents but no index forces find() to run a collection scan, reading every Document and getting slower as the data grows. Find slow queries with explain():

db.users.find({ email: "[email protected]" }).explain("executionStats")

If you see COLLSCAN, that field has no index yet. Add one:

db.users.createIndex({ email: 1 }, { unique: true })
db.orders.createIndex({ userId: 1, createdAt: -1 })   # compound index
db.users.getIndexes()                                 # list all indexes

Rule of thumb: Index only the fields you query or sort on frequently. Every index consumes disk and slightly slows inserts and updates, so do not pre-create one for every field.

When to Use MongoDB vs SQL

MongoDB is not universally better than MySQL/PostgreSQL — each suits a different kind of workload. Choosing wrong at the start forces awkward workarounds or a painful migration later. Decide based on your data shape and the query patterns of your app.

Choose MongoDB when

Choose SQL (MySQL / PostgreSQL) when

In practice: Many systems use both at once — SQL for core transactional data (users, orders, finance) and MongoDB for logs, activity feeds, or flexible-schema content. A single VPS can run both if it has enough RAM.

Essential mongosh Commands

Post-install Checklist

  1. Install from the official repo (not Ubuntu's default) to get the latest version
  2. Enable authorization: enabled immediately — never run production without auth
  3. Create separate users per database — never use the admin user from apps
  4. If you open remote access, always restrict source IPs via UFW
  5. Schedule daily mongodump and ship the dump off-host
  6. Watch disk usage — MongoDB consumes more disk than MySQL

Frequently Asked Questions

How much VPS RAM does MongoDB need?

For testing or a small site, 2 GB is enough to start, but MongoDB uses more RAM than MySQL because the WiredTiger cache tries to keep the working set in memory. As data grows or concurrent queries increase, 4 GB or more is recommended — and cap cacheSizeGB in the config so MongoDB does not starve other services on the VPS. AsiaGB VPS starts at 500 THB/month on SSD with RAM you choose.

Can MongoDB and MySQL run on the same VPS?

Yes, and it is very common. Many systems use MySQL for core transactional data and MongoDB for logs or flexible-schema content. They run on different ports (MySQL 3306, MongoDB 27017) and do not conflict, but make sure the VPS has enough RAM for both and set MongoDB's cacheSizeGB appropriately so they do not fight over memory.

What if I forget the MongoDB admin password?

Stop mongod, edit /etc/mongod.conf to temporarily disable authorization: enabled, restart, and enter mongosh without a password. Then run db.changeUserPassword("adminUser","NewPassword") to set a new one, re-enable authentication, and restart again. While auth is disabled, close remote access (set bindIp back to 127.0.0.1) or block the firewall first.

Can I back up with mongodump while the database is in use?

Yes — mongodump reads data online without stopping the service. For large, write-heavy databases the snapshot may not be 100% consistent, though; for precise point-in-time backups use a replica set with --oplog or a filesystem snapshot. For a typical website, a nightly cron mongodump shipped off-host is plenty.

Need a Reliable VPS for MongoDB?

AsiaGB Linux VPS with SSD from 500 THB/month. Plenty of RAM for MongoDB, full root access, locations in Thailand / Singapore.

View VPS Plans

View all affordable VPS Thailand plans →