15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
01.11.2024
3 +1

Complete Guide to MongoDB: Installation, Features & Best Practices on a VPS

MongoDB is one of the most powerful and widely adopted NoSQL databases in the world — and for good reason. Its flexible, document-oriented architecture makes it the go-to choice for developers building modern, data-intensive applications that need to scale fast. Whether you're running a startup MVP or managing enterprise-grade infrastructure, MongoDB paired with a high-performance hosting environment gives you the speed, flexibility, and reliability your applications demand.

In this comprehensive guide, you'll learn what MongoDB is, why it stands out from traditional relational databases, how to install it on Ubuntu, and how to perform essential operations using the MongoDB shell.

What Is MongoDB and Why Should You Use It?

MongoDB is an open-source, document-oriented NoSQL database that stores data in flexible, JSON-like documents called BSON (Binary JSON). Unlike traditional relational databases that rely on rigid table-row-column structures, MongoDB allows each document in a collection to have its own unique structure. This makes it exceptionally well-suited for applications with evolving or unpredictable data models.

Key Advantages of MongoDB Over Traditional SQL Databases

FeatureMongoDB (NoSQL)Traditional SQL
Data ModelFlexible documents (BSON)Fixed schema (tables/rows)
ScalabilityHorizontal (sharding)Primarily vertical
Schema ChangesSchema-less, dynamicRequires migrations
Query LanguageRich MQL + aggregationSQL
Best ForDynamic, unstructured dataStructured, relational data
Performance at ScaleExcellent with shardingCan degrade without tuning

MongoDB is ideal for a wide range of use cases including real-time analytics, content management systems, e-commerce platforms, IoT data ingestion, mobile backends, and any application where data structures are likely to change over time.

Why Host MongoDB on a VPS?

Hosting MongoDB on a dedicated virtual private server gives you a level of control, performance, and security that shared environments simply cannot provide. With a VPS Hosting plan from AlexHost, you get:

  • Full root access to configure MongoDB exactly as your application requires
  • Dedicated RAM and CPU resources to handle demanding read/write workloads
  • Isolated environment that eliminates the "noisy neighbor" problem common in shared hosting
  • Seamless vertical and horizontal scaling as your data grows
  • Custom firewall and network rules to lock down database access

For applications with exceptionally high throughput requirements, AlexHost's Dedicated Servers offer bare-metal performance with full hardware isolation — the gold standard for production MongoDB deployments.

Section 1: Understanding MongoDB's Core Architecture

Before diving into installation, it's important to understand how MongoDB organizes and manages data.

Documents

The fundamental unit of data in MongoDB is a document — a JSON-like object that can contain nested fields, arrays, and mixed data types. For example:

{
  "_id": ObjectId("64b1f2c3e4b0a1d2e3f4a5b6"),
  "name": "Alice",
  "age": 30,
  "email": "alice@example.com",
  "address": {
    "city": "New York",
    "zip": "10001"
  },
  "tags": ["developer", "mongodb", "nodejs"]
}

Collections

Documents are grouped into collections, which are analogous to tables in SQL databases. However, unlike SQL tables, collections do not enforce a fixed schema — documents within the same collection can have completely different fields.

Databases

A MongoDB server can host multiple databases, each containing its own set of collections. This makes it easy to isolate data for different applications or environments (e.g., development, staging, production) on a single server instance.

Section 2: Key Features of MongoDB

2.1 Document-Oriented Storage

MongoDB's document model is one of its most powerful features. Because each document can have a different structure, developers can evolve the database schema organically as application requirements change — without running complex ALTER TABLE migrations or experiencing downtime.

This flexibility is particularly valuable in agile development environments where requirements shift frequently, or in applications that aggregate data from multiple heterogeneous sources.

2.2 Horizontal Scalability with Sharding

One of MongoDB's defining capabilities is its native support for horizontal scaling through sharding. Sharding distributes data across multiple servers (called shards), allowing MongoDB to handle datasets and throughput levels that would overwhelm a single machine.

Each shard holds a subset of the total data, and a mongos router directs queries to the appropriate shard(s) based on a configurable shard key. This architecture enables near-linear scalability as your data volume and query load grow.

For high-traffic production environments, hosting MongoDB on AlexHost's Dedicated Servers ensures that each shard has access to isolated, high-performance hardware resources.

2.3 High Availability with Replica Sets

MongoDB provides built-in fault tolerance through replica sets — groups of MongoDB instances that maintain identical copies of the same data. A replica set consists of:

  • One primary node that receives all write operations
  • One or more secondary nodes that replicate data from the primary
  • An optional arbiter that participates in elections without storing data

If the primary node fails, the replica set automatically elects a new primary from the available secondaries, minimizing downtime and ensuring data durability.

2.4 Powerful Query Language and Aggregation Framework

MongoDB's MongoDB Query Language (MQL) supports a rich set of operations including:

  • Field-level filtering with comparison, logical, and element operators
  • Projection to return only specific fields
  • Sorting and pagination with sort(), limit(), and skip()
  • Text search with full-text indexes
  • Geospatial queries for location-based applications

The Aggregation Framework provides a pipeline-based approach to data transformation and analysis, supporting operations such as $match, $group, $sort, $project, $lookup (joins), $unwind, and many more — offering functionality comparable to complex SQL GROUP BY and JOIN operations.

2.5 Flexible Indexing

MongoDB supports multiple index types to optimize query performance:

  • Single-field indexes for simple queries
  • Compound indexes for multi-field queries
  • Multikey indexes for array fields
  • Text indexes for full-text search
  • Geospatial indexes for location queries
  • TTL indexes for automatic document expiration (useful for session data or logs)

Section 3: Installing MongoDB on Ubuntu (Step-by-Step)

This section walks you through a complete MongoDB installation on Ubuntu 20.04 LTS (Focal Fossa). These steps are optimized for an AlexHost VPS environment with root or sudo access.

Prerequisites

  • Ubuntu 20.04 LTS server
  • A user account with sudo privileges
  • Basic familiarity with the Linux command line

If you don't yet have a server, you can spin up a fully configured Ubuntu VPS in minutes with AlexHost VPS Hosting.

Step 1: Import the MongoDB GPG Public Key

MongoDB packages are signed with a GPG key to verify their authenticity. Import the key with the following command:

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

You should see OK as the output, confirming the key was imported successfully.

Step 2: Add the MongoDB Repository

Create a list file to add the official MongoDB repository to your system's package sources:

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

> Note: This command adds the MongoDB 6.0 repository. Adjust the version number if you need a different release.

Step 3: Update the Package Database

Refresh your local package index to include the newly added MongoDB repository:

sudo apt update

Step 4: Install MongoDB

Install the latest stable version of MongoDB with all required components:

sudo apt install -y mongodb-org

This installs the following packages:

  • mongod — the MongoDB database daemon
  • mongos — the MongoDB sharding router
  • mongosh — the MongoDB shell (modern replacement for the legacy mongo shell)
  • MongoDB tools and libraries

Step 5: Start and Enable the MongoDB Service

Start the MongoDB service immediately:

sudo systemctl start mongod

Enable MongoDB to start automatically on system boot:

sudo systemctl enable mongod

Verify that MongoDB is running correctly:

sudo systemctl status mongod

You should see output indicating that the service is active (running). If MongoDB started successfully, you'll also see a line confirming it's listening on port 27017.

Before using MongoDB in any production or internet-facing environment, it's critical to enable authentication. By default, MongoDB does not require a username or password.

Create an administrative user:

mongosh

Inside the MongoDB shell:

use admin

db.createUser({
  user: "adminUser",
  pwd: "YourStrongPasswordHere",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})

Enable authentication by editing the MongoDB configuration file:

sudo nano /etc/mongod.conf

Find the security section and add:

security:
  authorization: enabled

Restart MongoDB to apply the changes:

sudo systemctl restart mongod

From this point forward, all connections to MongoDB will require valid credentials.

Section 4: Using MongoDB — Essential Commands and Operations

With MongoDB installed and secured, let's explore the most important operations you'll use day-to-day.

Step 1: Access the MongoDB Shell

Connect to your MongoDB instance using the modern mongosh shell:

mongosh

If authentication is enabled, connect with credentials:

mongosh -u adminUser -p YourStrongPasswordHere --authenticationDatabase admin

Step 2: Database Operations

List all databases:

show dbs

Create or switch to a database:

use mydatabase

> MongoDB creates the database automatically when you first insert data into it.

Check the currently selected database:

db

Drop a database:

db.dropDatabase()

Step 3: Collection Operations

Create a collection explicitly:

db.createCollection("users")

List all collections in the current database:

show collections

Drop a collection:

db.users.drop()

Step 4: Document CRUD Operations

#### Insert Documents

Insert a single document:

db.users.insertOne({
  name: "Alice",
  age: 30,
  email: "alice@example.com",
  role: "developer"
})

Insert multiple documents at once:

db.users.insertMany([
  { name: "Bob", age: 25, email: "bob@example.com", role: "designer" },
  { name: "Carol", age: 35, email: "carol@example.com", role: "manager" },
  { name: "Dave", age: 28, email: "dave@example.com", role: "developer" }
])

#### Read Documents

Find all documents in a collection:

db.users.find()

Find documents with a specific condition:

db.users.find({ role: "developer" })

Find documents with multiple conditions:

db.users.find({ role: "developer", age: { $gte: 28 } })

Return only specific fields (projection):

db.users.find({ role: "developer" }, { name: 1, email: 1, _id: 0 })

Find a single document:

db.users.findOne({ name: "Alice" })

Sort results:

db.users.find().sort({ age: 1 })   // Ascending
db.users.find().sort({ age: -1 })  // Descending

Limit and paginate results:

db.users.find().limit(10).skip(20)  // Page 3 with 10 results per page

#### Update Documents

Update a single document:

db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31, role: "senior developer" } }
)

Update multiple documents:

db.users.updateMany(
  { role: "developer" },
  { $set: { department: "Engineering" } }
)

Increment a numeric field:

db.users.updateOne(
  { name: "Bob" },
  { $inc: { age: 1 } }
)

#### Delete Documents

Delete a single document:

db.users.deleteOne({ name: "Dave" })

Delete multiple documents matching a condition:

db.users.deleteMany({ role: "designer" })

Step 5: Indexing for Performance

Creating indexes on frequently queried fields dramatically improves query performance.

Create a single-field index:

db.users.createIndex({ email: 1 })

Create a compound index:

db.users.createIndex({ role: 1, age: -1 })

Create a unique index:

db.users.createIndex({ email: 1 }, { unique: true })

List all indexes on a collection:

db.users.getIndexes()

Step 6: Aggregation Pipeline

The aggregation framework allows you to perform complex data analysis directly within MongoDB.

Example: Count users by role and sort by count:

db.users.aggregate([
  { $group: { _id: "$role", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

Example: Filter, group, and calculate average age by role:

db.users.aggregate([
  { $match: { department: "Engineering" } },
  { $group: { _id: "$role", avgAge: { $avg: "$age" }, total: { $sum: 1 } } },
  { $sort: { avgAge: 1 } }
])

Section 5: MongoDB Configuration and Performance Tuning

Configuring mongod.conf

MongoDB's primary configuration file is located at /etc/mongod.conf. Key settings to review and optimize:

# Network settings
net:
  port: 27017
  bindIp: 127.0.0.1  # Restrict to localhost for security; use server IP for remote access

# Storage settings
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      cacheSizeGB: 2  # Set to ~50% of available RAM

# Logging
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Security
security:
  authorization: enabled

# Replication (for replica sets)
replication:
  replSetName: "rs0"

Performance Best Practices

  1. Allocate sufficient RAM — MongoDB's WiredTiger storage engine uses an in-memory cache. Set cacheSizeGB to approximately 50% of available system RAM.
  2. Use appropriate indexes — Analyze slow queries with db.collection.explain("executionStats") and create indexes accordingly.
  3. Monitor with MongoDB Atlas or mongostat — Use mongostat and mongotop command-line tools to monitor real-time performance.
  4. Enable journaling — Journaling is enabled by default and provides crash recovery; do not disable it in production.
  5. Use connection pooling — Configure your application's MongoDB driver to use connection pooling to reduce connection overhead.
  6. Regularly compact collections — Use db.runCommand({ compact: "collectionName" }) to reclaim disk space after large deletions.

Section 6: Backing Up and Restoring MongoDB

Regular backups are essential for any production database. MongoDB provides built-in tools for this purpose.

Create a Backup with mongodump

mongodump --uri="mongodb://adminUser:password@localhost:27017" --out=/backup/mongodb/$(date +%Y%m%d)

Restore from a Backup with mongorestore

mongorestore --uri="mongodb://adminUser:password@localhost:27017" /backup/mongodb/20240115/

Automate Backups with Cron

Add a cron job to run daily backups automatically:

sudo crontab -e

Add the following line to run a backup every day at 2:00 AM:

0 2 * * * mongodump --uri="mongodb://adminUser:password@localhost:27017" --out=/backup/mongodb/$(date +%Y%m%d) >> /var/log/mongodb-backup.log 2>&1

Choosing the Right AlexHost Plan for MongoDB

The right hosting plan depends on your application's scale, traffic, and data requirements:

Use CaseRecommended PlanWhy
Development / TestingVPS HostingCost-effective, full control, easy setup
Small to Medium ProductionVPS HostingScalable resources, SSD storage, root access
High-Traffic ProductionDedicated ServersBare-metal performance, no resource sharing
ML/AI with MongoDBGPU HostingGPU acceleration for data processing workloads
Web App + MongoDBVPS with cPanelEasy management interface alongside your database

For applications that also require a web frontend, email notifications, or SSL-secured connections, AlexHost offers SSL Certificates and Email Hosting to complete your infrastructure stack.

Frequently Asked Questions

Q: Is MongoDB free to use?

Yes. MongoDB Community Edition is free and open-source under the Server Side Public License (SSPL). MongoDB Enterprise and MongoDB Atlas (cloud) offer additional features on a paid basis.

Q: What port does MongoDB use by default?

MongoDB listens on port 27017 by default. You can change this in /etc/mongod.conf.

Q: Can I run MongoDB on a shared hosting plan?

MongoDB requires root or administrative access to install and configure properly, which is not available on standard shared hosting. A VPS or dedicated server is required. AlexHost's Shared Web Hosting is better suited for PHP/MySQL applications, while MongoDB deployments should use a VPS or dedicated server.

Q: How do I connect to MongoDB from a remote application?

Update bindIp in /etc/mongod.conf to include your server's IP address, configure your firewall to allow port 27017 from trusted IPs only, and use a connection string in the format: mongodb://username:password@your-server-ip:27017/dbname.

Q: What is the difference between MongoDB and MySQL?

MySQL is a relational database that uses structured tables and SQL. MongoDB is a NoSQL document database that stores flexible JSON-like documents. MongoDB excels at handling unstructured or semi-structured data and horizontal scaling, while MySQL is better suited for applications with complex relational data and strict ACID compliance requirements.

Conclusion

MongoDB is a transformative database technology that empowers developers to build modern, scalable applications without the constraints of rigid relational schemas. Its document-oriented model, native horizontal scaling through sharding, built-in high availability via replica sets, and powerful aggregation framework make it one of the most versatile databases available today.

By hosting MongoDB on an AlexHost VPS Hosting plan, you get the full control, dedicated resources, and reliable infrastructure needed to run MongoDB effectively — whether you're prototyping your first application or managing a high-traffic production system.

Follow the installation and configuration steps in this guide to get your MongoDB instance up and running, implement proper security measures from day one, and leverage indexing and the aggregation pipeline to build performant, data-driven applications.

Have questions about your MongoDB setup or need help choosing the right hosting plan? AlexHost's expert support team is available 24/7 to assist you every step of the way.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started