Andrew Mercer
on this page

MongoDB Overview

MongoDB is a document-oriented database — collections of BSON (binary JSON) documents rather than rows in fixed-schema tables. This section covers install, everyday shell use, Security, Replication, Sharding, and Troubleshooting.

Install (Debian/Ubuntu)

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
sudo apt-get update
sudo aptitude -y install mongodb-org mongodb-org-server

This pins an old release series (3.2) for format reference — check the current MongoDB installation docs for the release and repo URL matching the version you actually want; apt-key itself is also deprecated in favor of a keyring file, similar to the change covered in the PostgreSQL and MySQL/MariaDB docs' package-repo sections.

systemd Unit

# /etc/systemd/system/mongodb.service
[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target

[Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]
WantedBy=multi-user.target
sudo systemctl start mongodb.service
sudo systemctl enable mongodb.service

Connecting

mongo                      # connect to the default instance
mongo db_name               # connect directly to a specific database
> use db_name

Or, remotely with authentication (see Security for setting this up):

mongo admin --host mongo_host -u admin_user -p

Basic Shell Operations

> show collections
db.products.find()                                   // view documents in a collection
db.products.count()                                    // count documents
db.products.find( {}, { "name": 1 } )                   // project a single field
db.products.find().toArray()                             // materialize as an array
db.products.find().limit(10).toArray()                     // limit results

// Filtering
db.products.find( {} ).limit(2)
db.products.find( {} ).limit(2).skip(10).sort( { "name": 1 } )  // sort, with pagination
db.products.find( {}, { "limits": 0 } )                          // exclude a field from output
// Update operations — covered at a "todo" level in the source notes:
db.collection.update(...)
db.collection.updateOne(...)
db.collection.updateMany(...)

For the specifics of these three, see the MongoDB update documentation — the short version is updateOne/updateMany are the modern, explicit-intent forms; plain update() behaves differently depending on whether the update document contains operators ($set, etc.) or is a full replacement, which is exactly the kind of ambiguity updateOne/updateMany were introduced to avoid.

Importing Data

mongoimport --db pcat --type json --file ~/pcat.json
mongoimport --port 27018 --db video --collection movies < ~/path/to/movies.json

Spinning Up a Throwaway Instance to Test an Import

mkdir -p /tmp/mongo/mongoimport
mkdir -p /tmp/mongo/mongoimport_logs
touch /tmp/mongo/mongoimport_logs/mongoimport.log
mongod --dbpath /tmp/mongo/mongoimport --port 27018 \
  --logpath /tmp/mongo/mongoimport_logs/mongoimport.log \
  --logappend --oplogSize 50 --fork
mongoimport --port 27018 --db pcat --collection products < ~/path/to/products.json
connected to: localhost:27018
imported 11 documents

Starting a Standalone Instance for Testing

mongod --dbpath /path/to/db --port 27018 --fork --logpath /path/to/logs

# With TLS
mongod --sslMode requireSSL --sslPEMKeyFile /path/to/keyfile.pem --sslCAFile /path/to/CAfile.pem \
  --dbpath /path/to/db --port 27018 --fork --logpath /path/to/logs

# With auth enabled
mongod --dbpath /path/to/db --port 27018 --fork --logpath /path/to/logs --auth
mongo --host your_host --port 27018
mongo --host your_host --port 27018 --ssl --sslPEMKeyFile /path/to/keyfile.pem --sslCAFile /path/to/CAfile.pem

Dropping a Database

show dbs
use db_name
db.dropDatabase()

Flushing OS-Level Caches (Not MongoDB-Specific)

Occasionally useful when troubleshooting whether slow behavior is a MongoDB issue or an OS page-cache artifact — this drops the Linux kernel's page cache, not any MongoDB-internal cache:

# 0 = reset, 1 = drop page cache, 2 = drop page cache plus dentries/inodes, 3 = drop everything
sudo sysctl -w vm.drop_caches=1
# or, to be certain everything is dropped:
sudo sysctl -w vm.drop_caches=3

Treat this as a diagnostic tool, not a routine maintenance step — dropping the page cache on a live production instance will cause a temporary spike in disk I/O as MongoDB re-reads data that was previously served from cache.

GUI Clients

See the general database GUI clients doc for DBeaver, MongoDB Compass, and other options — it's no longer specific to MongoDB, so it's covered there rather than here.