MongoDB Reference

Document database with flexible schema, aggregation pipeline, and rich query operators.

CLI Basics

Connect with mongosh
# Local instance
mongosh

# Remote with authentication
mongosh "mongodb://user:pass@db.example.com:27017/myapp"

# Connection string with replica set
mongosh "mongodb://host1:27017,host2:27017/myapp?replicaSet=rs0"
Navigation commands
show dbs                        // list databases
use myapp                       // switch database
show collections                // list collections in current db
db.stats()                      // database statistics
db.devices.stats()              // collection statistics

CRUD Operations

Insert documents
// Insert one
db.devices.insertOne({
    hostname: "sw-core-01",
    ip: "10.50.1.10",
    type: "switch",
    vlans: [10, 20, 30],
    config: { ssh: true, snmp: "v3" }
})

// Insert many
db.devices.insertMany([
    { hostname: "sw-dist-01", type: "switch" },
    { hostname: "ap-lobby-01", type: "ap" }
])
Find (query) documents
// All documents
db.devices.find()

// Filter by field
db.devices.find({ type: "switch" })

// Multiple conditions (implicit AND)
db.devices.find({ type: "switch", "config.ssh": true })

// OR condition
db.devices.find({ $or: [{ type: "switch" }, { type: "router" }] })

// Comparison operators
db.devices.find({ vlans: { $gt: 20 } })           // greater than
db.devices.find({ hostname: { $regex: /^sw-/ } })  // regex match

// Projection: return specific fields only
db.devices.find({ type: "switch" }, { hostname: 1, ip: 1, _id: 0 })

// Sort, limit, skip
db.devices.find().sort({ hostname: 1 }).limit(10).skip(20)
Update documents
// Update one: set fields
db.devices.updateOne(
    { hostname: "sw-core-01" },
    { $set: { vlan: 20, updated_at: new Date() } }
)

// Update many
db.devices.updateMany(
    { type: "switch" },
    { $set: { monitored: true } }
)

// Push to array
db.devices.updateOne(
    { hostname: "sw-core-01" },
    { $push: { vlans: 40 } }
)

// Upsert: insert if not found
db.devices.updateOne(
    { hostname: "sw-new-01" },
    { $set: { type: "switch", ip: "10.50.1.15" } },
    { upsert: true }
)
Delete documents
db.devices.deleteOne({ hostname: "sw-core-01" })
db.devices.deleteMany({ type: "ap", monitored: false })

Indexes

Create and manage indexes
// Single field index
db.devices.createIndex({ hostname: 1 })            // 1 = ascending

// Compound index
db.devices.createIndex({ type: 1, hostname: 1 })

// Unique index
db.devices.createIndex({ hostname: 1 }, { unique: true })

// TTL index: auto-delete documents after expiry
db.sessions.createIndex({ created_at: 1 }, { expireAfterSeconds: 3600 })

// Text index for full-text search
db.logs.createIndex({ message: "text" })
db.logs.find({ $text: { $search: "error timeout" } })

// List indexes
db.devices.getIndexes()

// Drop index
db.devices.dropIndex("hostname_1")

Aggregation Pipeline

The aggregation pipeline processes documents through stages. Each stage transforms the document stream.

Group and count
db.devices.aggregate([
    { $match: { type: "switch" } },
    { $group: {
        _id: "$location",
        count: { $sum: 1 },
        devices: { $push: "$hostname" }
    }},
    { $sort: { count: -1 } }
])
Lookup (left join equivalent)
db.orders.aggregate([
    { $lookup: {
        from: "customers",
        localField: "customer_id",
        foreignField: "_id",
        as: "customer"
    }},
    { $unwind: "$customer" },
    { $project: {
        order_id: "$_id",
        total: 1,
        customer_name: "$customer.name"
    }}
])

Backup and Restore

mongodump and mongorestore
# Dump single database
mongodump --db myapp --out backup_$(date +%F)/

# Dump single collection
mongodump --db myapp --collection devices --out backup/

# Restore
mongorestore --db myapp backup_2026-04-10/myapp/

# Dump as JSON (human-readable)
mongoexport --db myapp --collection devices --out devices.json
mongoimport --db myapp --collection devices --file devices.json

Python Integration

pymongo basics
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
db = client.myapp

# Insert
db.devices.insert_one({"hostname": "sw-core-01", "type": "switch"})

# Find
for device in db.devices.find({"type": "switch"}):
    print(device["hostname"])

# Update
db.devices.update_one(
    {"hostname": "sw-core-01"},
    {"$set": {"vlan": 20}}
)

# Aggregation
pipeline = [
    {"$group": {"_id": "$type", "count": {"$sum": 1}}},
    {"$sort": {"count": -1}}
]
for result in db.devices.aggregate(pipeline):
    print(f"{result['_id']}: {result['count']}")