MongoDB Cheatsheet

CRUD, queries, aggregation, indexes & mongosh commands

Database
Contents
🔗

Connection

# mongosh (Mongo Shell)
mongosh
mongosh "mongodb://localhost:27017/mydb"
mongosh "mongodb+srv://user:pass@cluster.mongodb.net/mydb"

# Basic commands
show dbs                      # list databases
use mydb                      # switch/create database
show collections              # list collections
db.stats()                    # database stats
db.dropDatabase()             # delete database
📝

CRUD Operations

# INSERT
db.users.insertOne({ name: "Alice", age: 25 })
db.users.insertMany([
  { name: "Bob", age: 30 },
  { name: "Carol", age: 28 }
])

# FIND (Read)
db.users.find()                          # all docs
db.users.find({ age: 25 })               # filter
db.users.findOne({ name: "Alice" })      # first match
db.users.find({}, { name: 1, _id: 0 })  # projection
db.users.find().sort({ age: -1 })        # sort desc
db.users.find().limit(5).skip(10)       # pagination
db.users.countDocuments({ age: { $gt: 25 } })

# UPDATE
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 26 } }
)
db.users.updateMany(
  { age: { $lt: 18 } },
  { $set: { status: "minor" } }
)
db.users.replaceOne({ name:"Alice" }, { name:"Alice", age:27 })

# DELETE
db.users.deleteOne({ name: "Bob" })
db.users.deleteMany({ age: { $lt: 18 } })
db.users.drop()                          # drop collection
🔍

Query Operators

# Comparison
$eq    $ne    $gt    $gte    $lt    $lte
$in    $nin

db.users.find({ age: { $gte: 18, $lte: 65 } })
db.users.find({ status: { $in: ["active", "pending"] } })

# Logical
$and   $or   $not   $nor

db.users.find({ $or: [{ age: 25 }, { name: "Bob" }] })

# Element
$exists    $type

# Array
$all   $elemMatch   $size

# Regex
db.users.find({ name: /^A/i })
✏️

Update Operators

# Field
$set        # set field value
$unset      # remove field
$inc        # increment
$mul        # multiply
$rename     # rename field
$min  $max  # update if less/greater

# Array
$push       # add to array
$pull       # remove from array
$addToSet   # add if unique
$pop        # remove first/last

# Example
db.users.updateOne(
  { name: "Alice" },
  { $inc: { age: 1 }, $push: { tags: "vip" } }
)
📊

Aggregation Pipeline

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: {
      _id: "$category",
      total: { $sum: "$amount" },
      count: { $sum: 1 },
      avg: { $avg: "$amount" }
  }},
  { $sort: { total: -1 } },
  { $limit: 10 }
])

# Common stages
$match      # filter documents
$group      # group & aggregate
$sort       # sort results
$project    # reshape / select fields
$limit      # limit results
$skip       # skip results
$unwind     # deconstruct array
$lookup     # join collections

Indexes

# Create
db.users.createIndex({ email: 1 })             # ascending
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ name: 1, age: -1 })   # compound
db.users.createIndex({ bio: "text" })           # text index

# List & drop
db.users.getIndexes()
db.users.dropIndex("email_1")

# Explain query
db.users.find({ email: "a@b.com" }).explain("executionStats")
🔧

Administration

# Export / Import
mongodump --db mydb --out /backup/
mongorestore --db mydb /backup/mydb/
mongoexport --db mydb --collection users --out users.json
mongoimport --db mydb --collection users --file users.json

# Users
db.createUser({ user:"admin", pwd:"pass", roles:["readWrite"] })

# Replication status
rs.status()