MongoDB Installation, Configuration, and Operations Guide

Installation

MongoDB 5.0 Installation

Refer to the official documentation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/

MongoDB 3.4 Installation (Tarball Method)

The yum repository for 3.4 is no longer available, so manual installation via tarball is required.

sudo groupadd mongod
sudo useradd -r -g mongod -s /sbin/nologin mongod

curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.24.tgz
tar -zxvf mongodb-linux-x86_64-3.4.24.tgz
cd mongodb-linux-x86_64-3.4.24

mkdir -p /usr/local/mongodb/
sudo cp -R bin /usr/local/mongodb/

echo -e "#mongodb\nexport PATH=/usr/local/mongodb/bin:$PATH" >> /etc/profile
vi /etc/profile
export PATH=/usr/local/mongodb/bin:$PATH
source /etc/profile

mkdir -p /var/lib/mongo
mkdir -p /var/log/mongodb

chown -R mongod:mongod /var/lib/mongo
chown -R mongod:mongod /var/log/mongodb

MongoDB 5.0 via Yum Repoistory

sudo touch /etc/yum.repos.d/mongodb-org-5.0.repo
sudo chmod 666 /etc/yum.repos.d/mongodb-org-5.0.repo

sudo cat >> /etc/yum.repos.d/mongodb-org-5.0.repo << 'EOF'
[mongodb-org-5.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc
EOF

sudo yum install -y mongodb-org
sudo systemctl start mongod

Note: When using heredoc syntax in scripts, ensure proper escaping of special charactres like $.

Configuration Files

MongoDB 3.4 Configuration (/etc/mongod.conf)

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

storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

net:
  port: 27017
  bindIp: 127.0.0.1

security:
  authorization: enabled

MongoDB 5.0 Configuration (/etc/mongod.conf)

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

storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

processManagement:
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27017
  bindIp: 127.0.0.1

systemd Service Configuration

Service Unit for Tarball Installation

[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network-online.target
Wants=network-online.target

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /etc/mongod.conf"
EnvironmentFile=-/etc/sysconfig/mongod
ExecStart=/usr/local/mongodb/bin/mongod $OPTIONS
ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb
ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb
ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb
PermissionsStartOnly=true
PIDFile=/var/run/mongodb/mongod.pid
Type=forking

LimitFSIZE=infinity
LimitCPU=infinity
LimitAS=infinity
LimitNOFILE=64000
LimitNPROC=64000
LimitMEMLOCK=infinity
TasksMax=infinity
TasksAccounting=false

[Install]
WantedBy=multi-user.target

Troubleshooting: Service Timeout Issues

If systemctl start mongod fails with a timeout error:

The issue occurs because Type=forking is specified in the service file, but the configuration lacks the corresponding processManagement settings.

Solution 1: Add forking configuration to /etc/mongod.conf:

processManagement:
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

Solution 2: Change service type to simple by creating an override file:

sudo systemctl edit mongod
[Service]
Type=simple

Troubleshooting: Service Fails to Start After Reboot

If MongoDB doesn't start automatically after system reboot with error status 48:

The service lacks network dependency. Add After=network-online.target and Wants=network-online.target to the [Unit] section.

User Management

Creating Administrative Users

use admin

db.createUser({
  user: "admin",
  pwd: "password",
  roles: [{ role: "root", db: "admin" }]
})

Creating Application Users

db.createUser({
  user: "appuser",
  pwd: "password",
  roles: ["readWrite"]
})

// Create user for specific database with dbOwner role
use mydatabase
db.createUser({
  user: "dbowner",
  pwd: "password",
  roles: ["dbOwner"]
})

Built-in Roles Reference

Database User Roles:

  • read: Read-only access
  • readWrite: Read and write access

Database Administration Roles:

  • dbAdmin: Administrative operations on current database
  • dbOwner: Full access to current database
  • userAdmin: User management on current database

Backup and Restoration Roles:

  • backup
  • restore

All-Database Roles:

  • readAnyDatabase
  • readWriteAnyDatabase
  • userAdminAnyDatabase
  • dbAdminAnyDatabase

Cluster Administration Roles:

  • clusterAdmin: Full cluster management
  • clusterManager: Cluster management and monitoring
  • clusterMonitor: Read-only monitoring access
  • hostManager: Server management

Querying Users

// View all users
use admin
db.system.users.find().pretty()

// View custom roles
db.system.roles.find().pretty()

// View users in current database
use mydatabase
show users

Authentication Connection Examples

mongo --host hostname --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"
mongo mongodb://user:password@ip:27017/database

Operations

Connection Statistics

db.serverStatus().connections

Output fields:

  • current: Active connections
  • available: Available connections
  • totalCreated: Total connections created since startup

Identifying Long-Running Queries

// Find queries performing collection scans
db.adminCommand({ 
  currentOp: true, 
  "planSummary": "COLLSCAN" 
})

// Find queries running longer than 3 seconds
db.adminCommand({ 
  currentOp: true, 
  "secs_running": { "$gt": 3 } 
})

Lock Monitoring

db.serverStatus().globalLock

WiredTiger limits maximum read/write concurrency to 128. If requests exceed this threshold, they queue up in currentQueue.readers/writers.

High lock queue indicates:

  • System concurrency is too high
  • Long-running operations (like foreground index builds) are holding locks

Optimization approaches:

  • Optimize query patterns (create indexes to avoid COLLSCAN)
  • Upgrade backend resources (memory, disk I/O, CPU)

Terminating Operations

db.killOp(opid)

Index Operations

// View all indexes
db.collection.getIndexes()

// View total index size
db.collection.totalIndexSize()

// Create index (background)
db.collection.createIndex(
  { field1: 1, field2: -1 }, 
  { background: true }
)

// Create hashed index for sharding
db.collection.createIndex(
  { shardKey: "hashed" }
)

// Drop specific index
db.collection.dropIndex("index_name")

// Drop all indexes
db.collection.dropIndexes()

Index creation options:

  • background: Build index in background (default: false)
  • unique: Create unique index (default: false)
  • name: Custom index name
  • dropDups: Remove duplicate entries
  • sparse: Index only documents with the field (default: false)
  • weights: Index weight for text search

Disk Space Management

Method 1: Immediate Release

db.dropDatabase()
db.collection.drop()

Method 2: Deferred Release via Compaction

// Remove documents (physical space not reclaimed)
db.collection.remove({ field: value })

// Compact to reclaim space (blocks all read/write operations)
db.runCommand({ compact: "collection_name" })

Common Shell Commands

// Show current database
db

// List databases
show dbs

// Switch/create database
use mydatabase

// List collections
show collections

// View single document
db.collection.findOne()

// Count documents
db.collection.countDocuments({})

// View database version
db.version()

Query Examples

Basic Queries

// Project specific fields
db.results.find({}, {_id: 1}).sort({_id: 1})

// Equality query
db.collection.find({"hash": "value"}).pretty()

// Pagination using _id
db.results.find({_id: {$gte: "last_id"}}, {_id: 1})
  .sort({_id: 1}).limit(10)

Comparison Operators

$eq    // Equal
$ne    // Not equal
$lt    // Less than
$lte   // Less than or equal
$gt    // Greater than
$gte   // Greater than or equal
$in    // In array
$nin   // Not in array

Logical Operators

// AND
db.inventory.find({
  $and: [
    { price: { $ne: 1.99 } },
    { price: { $exists: true } }
  ]
})

// OR
db.collection.find({
  date: ISODate("2016-12-28T00:00:00Z"),
  $or: [
    { index_code: /^80/ },
    { index_code: /^85/ }
  ]
})

Field Existence and Type Queries

// Check if field exists
db.inventory.find({ qty: { $exists: true } })

// Field exists but not in specific array
db.inventory.find({
  qty: { $exists: true, $nin: [5, 15] }
})

// Query by BSON type
db.addressBook.find({ "zipCode": { $type: "string" } })

// Field is null (type 10)
db.collection.find({
  CancelDate: { $not: { $type: 10 } }
})

Aggregation with Grouping

db.collection.aggregate([
  {
    $group: {
      _id: {
        field1: "$field1",
        field2: "$field2"
      }
    }
  }
])

Regex/Pattern Matching

db.collection.find({name: {$regex: /pattern/, $options: "si"}})

Update Operations

// Update with $in
db.inventory.update(
  { tags: { $in: ["appliances", "school"] } },
  { $set: { sale: true } }
)

Batch Updates with forEach

db.results.find().forEach(function(doc) {
  db.results.update(
    { _id: doc._id },
    { $set: { source: [doc.source] } }
  )
})

Query Execution Analysis

db.test.find({field: "value", systime: 16000000}).explain("executionStats")

Replication

Replica Set Initialization

rs.initiate({
  _id: "replica-set-name",
  members: [
    { _id: 0, host: "192.168.1.10:27017" },
    { _id: 1, host: "192.168.1.11:27017" }
  ]
})

Reconfiguring Replica Set

When replica set is already initialized but needs reconfiguration:

rsconf = rs.conf()
rsconf.members = [
  { _id: 0, host: "192.168.1.10:27017" },
  { _id: 1, host: "192.168.1.11:27017" }
]
rs.reconfig(rsconf, {force: true})

Useful Replica Set Commands

rs.help()      // Display help
rs.status()     // View replica set status
rs.conf()       // View configuration

Sharded Cluster

Prerequisites

  1. Deploy config servers as replica set
  2. Deploy shard servers
  3. Enable authentication with keyfile
  4. Configure firewall rules to allow inter-node communication

Config Server Setup

rs.initiate({
  _id: "shard-config-server",
  configsvr: true,
  members: [
    { _id: 0, host: "192.168.1.20:27017" }
  ]
})

Shard Server Setup

rs.initiate({
  _id: "shard-shard-server",
  members: [
    { _id: 0, host: "192.168.1.21:27017" },
    { _id: 1, host: "192.168.1.22:27017" }
  ]
})

User Setup for Cluster

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

db.getSiblingDB("admin").auth("admin", "password")

db.getSiblingDB("admin").createUser({
  user: "clusteradmin",
  pwd: "password",
  roles: [{ role: "clusterAdmin", db: "admin" }]
})

Adding Shards

sh.addShard("shard-shard-server/192.168.1.21:27017")

Enabling Sharding

sh.enableSharding("mydatabase")

Sharding a Collection

// Range-based sharding
sh.shardCollection("mydatabase.collection", { "age": 1 })

// Hash-based sharding
sh.shardCollection("mydatabase.collection", { "userId": "hashed" })

Viewing Cluster Status

sh.status()

Common Sharding Issues

Config server not detected:

Ensure config server replica set is running and accessible. Check:

  • Config server is running (ps aux | grep mongod)
  • Replica set initialized (rs.status())
  • Firewall allows connections on port 27017
  • Hostnames resolve correctly

Backup and Restore

Logical Backup with mongodump

# Single database backup
mongodump --db mydatabase --out /backup/path

# Full cluster backup
mongodump --host mongos-host --port 27017

# Restore
mongorestore --db mydatabase /backup/path/mydatabase

Physical Backup via Filesystem Snapshots

Requires WiredTiger storage engine and volume-level snapshot support (LVM, cloud snapshots).

Memory and Storage Management

Memory

MongoDB uses mmap for memory management. High memory usage (100%) is normal and typically not a concern. Memory is not released after operations but will be reused.

Storage

MongoDB pre-allocates data files. Operations like drop, remove, and compact do not immediately release disk space—they enable reuse of pre-allocated space.

When disk usage approaches 100%:

  • Upgrade disk capacity
  • Create secondary member and sync data, then trigger failover
  • Use db.repairDatabase() (blocks all operations—use with caution)

Read Concern Configuration

For MongoDB 3.6+, readConcern: "majority" requires:

db.serverStatus().storageEngine  // Must be WiredTiger
rs.conf().protocolVersion        // Must be 1 (pv1)
db.adminCommand({getParameter: 1, featureCompatibilityVersion: 1})  // Version 3.6+

Verification

After installation, verify MongoDB is running:

mongosh

Check the log file for successful startup:

[initandlisten] waiting for connections on port 27017

Data Storage Recommendations

  • Store timestamps as strings for consistency across applications
  • MongoDB is schema-free—databases and collections are created automatically on first document insertion
  • Always create indexes on shard keys before enabling sharding on populated collections

Tags: mongodb database installation Sharding Replication

Posted on Tue, 22 Sep 2026 16:51:54 +0000 by carlmcdade