Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 70 ยท Practice and wrap-up

MongoDB Cheat Sheet

A one-page MongoDB reference for mongosh: CRUD, query and update operators, aggregation stages, indexes, explain and admin commands, with short examples.

This is the page to keep open in a second tab. It lists the mongosh commands and operators you will use most, grouped by task, with a one-line example each. Every snippet is real mongosh syntax and read-only: the site has no MongoDB server, so nothing here runs in the browser. To practice the ideas on the stand-in engine, use the exercises in Practice: Query and Update Exercises and Practice: Aggregation Exercises.

Examples use a shop database with products and orders collections. Operators and options can differ slightly between server versions, so check the manual for your version when it matters.

Shell and databases

JavaScript
show dbs                      // list databases
use shop                      // switch (created on first write)
db                            // current database name
show collections              // list collections
db.getCollectionNames()       // same, as an array
db.products.drop()            // delete a collection and its indexes
db.dropDatabase()             // delete the current database
db.stats()                    // database size information
db.products.countDocuments({})  // exact count
db.products.estimatedDocumentCount()  // fast approximate count from metadata

Insert

JavaScript
db.products.insertOne({ name: "Mug", price: 9, tags: ["kitchen"] })
db.products.insertMany([{ name: "Cap" }, { name: "Pen" }])
db.products.insertMany(docs, { ordered: false })   // continue after an error

Find

JavaScript
db.products.find()                              // all documents (cursor)
db.products.findOne({ name: "Mug" })            // first match or null
db.products.find({ price: 9 })                  // equality
db.products.find({ "address.city": "Oslo" })    // dot notation for nesting
db.products.find({ tags: "kitchen" })           // array contains value
db.products.find({}, { name: 1, price: 1, _id: 0 })   // projection
db.products.find().sort({ price: -1 }).skip(20).limit(10)
db.products.distinct("tags")

Projection rules: use inclusion (1) or exclusion (0) for fields, not both, except that _id may be excluded in an inclusion projection.

Query operators

Group Operators
Comparison $eq $ne $gt $gte $lt $lte $in $nin
Logical $and $or $nor $not
Element $exists $type
Evaluation $regex $expr $mod $jsonSchema $text
Array $all $elemMatch $size
JavaScript
db.products.find({ price: { $gte: 5, $lt: 20 } })
db.products.find({ category: { $in: ["kitchen", "office"] } })
db.products.find({ $or: [{ stock: 0 }, { discontinued: true }] })
db.products.find({ discount: { $exists: true } })
db.products.find({ name: { $regex: "^mu", $options: "i" } })
db.products.find({ $expr: { $gt: ["$price", "$cost"] } })
db.orders.find({ items: { $elemMatch: { sku: "A1", qty: { $gt: 2 } } } })
db.products.find({ tags: { $all: ["kitchen", "gift"] } })
db.products.find({ tags: { $size: 2 } })

A filter with several fields is an implicit AND. { field: null } matches null and missing; { field: { $exists: false } } matches only missing.

Update

JavaScript
db.products.updateOne({ name: "Mug" }, { $set: { price: 10 } })
db.products.updateMany({ stock: 0 }, { $set: { available: false } })
db.products.replaceOne({ name: "Mug" }, { name: "Mug", price: 11 })
db.products.updateOne(filter, update, { upsert: true })
db.products.findOneAndUpdate(
  { name: "Mug" }, { $inc: { stock: -1 } },
  { returnDocument: "after" }
)

Update operators

Operator Effect
$set / $unset Set or remove fields
$inc / $mul Add to or multiply a number
$min / $max Keep the smaller or larger value
$rename Rename a field
$currentDate Set to the current date
$setOnInsert Set only when an upsert inserts
$push / $addToSet Append to an array (the latter only if absent)
$pull / $pop Remove matching elements, or the first or last element
$each $position $slice $sort Modifiers for $push
JavaScript
db.products.updateOne({ _id: 1 }, { $push: { tags: { $each: ["new", "gift"] } } })
db.products.updateOne({ _id: 1 }, { $pull: { tags: "old" } })
db.orders.updateOne({ _id: 5, "items.sku": "A1" }, { $set: { "items.$.qty": 3 } })
db.orders.updateOne({ _id: 5 }, { $inc: { "items.$[].qty": 1 } })
db.orders.updateOne(
  { _id: 5 }, { $set: { "items.$[i].shipped": true } },
  { arrayFilters: [{ "i.qty": { $gt: 2 } }] }
)

Delete and bulk

JavaScript
db.products.deleteOne({ _id: 1 })
db.products.deleteMany({ discontinued: true })
db.products.bulkWrite([
  { insertOne: { document: { name: "Lid" } } },
  { updateOne: { filter: { name: "Cap" }, update: { $set: { price: 7 } } } },
  { deleteOne: { filter: { name: "Pen" } } }
], { ordered: false })

Aggregation

JavaScript
db.orders.aggregate([
  { $match: { status: "paid" } },
  { $group: { _id: "$customerId", total: { $sum: "$amount" }, n: { $sum: 1 } } },
  { $sort: { total: -1 } },
  { $limit: 5 }
])
Stage Purpose
$match Filter documents (put early, can use indexes)
$project / $addFields / $set / $unset Reshape fields
$group Group and accumulate
$sort / $limit / $skip Order and trim
$unwind One document per array element
$lookup Left outer join with another collection
$count / $sortByCount Counting shortcuts
$facet Several sub-pipelines on the same input
$bucket / $bucketAuto Histogram-style grouping
$replaceRoot Promote a subdocument to the top
$unionWith Append another collection's documents
$setWindowFields Window functions (running totals, ranks)
$out / $merge Write results to a collection

Common accumulators: $sum, $avg, $min, $max, $first, $last, $push, $addToSet. Common expression operators: $add, $subtract, $multiply, $divide, $cond, $switch, $ifNull, $concat, $toUpper, $size, $map, $filter, $reduce, $dateToString.

JavaScript
db.orders.aggregate([
  { $lookup: { from: "customers", localField: "customerId",
               foreignField: "_id", as: "customer" } },
  { $unwind: "$customer" },
  { $project: { _id: 0, amount: 1, name: "$customer.name" } }
])

Indexes

JavaScript
db.products.createIndex({ name: 1 })                       // single field
db.products.createIndex({ category: 1, price: -1 })        // compound
db.products.createIndex({ email: 1 }, { unique: true })
db.products.createIndex({ stock: 1 }, { partialFilterExpression: { stock: { $gt: 0 } } })
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })  // TTL
db.products.createIndex({ title: "text", body: "text" })
db.products.getIndexes()
db.products.dropIndex("name_1")

Guidelines: order compound fields Equality, Sort, Range; an index serves queries on its leading fields (a prefix); every extra index slows writes.

explain and diagnostics

JavaScript
db.products.find({ category: "kitchen" }).explain("executionStats")
db.orders.aggregate(pipeline).explain("executionStats")
db.setProfilingLevel(1, { slowms: 100 })      // profile slow operations
db.system.profile.find().sort({ ts: -1 }).limit(5)
db.currentOp()                                // running operations
db.killOp(opId)                               // stop one

Read the plan for IXSCAN (index) versus COLLSCAN (full scan), and compare totalDocsExamined with nReturned.

Validation and collections

JavaScript
db.createCollection("users", {
  validator: { $jsonSchema: {
    bsonType: "object",
    required: ["email"],
    properties: { email: { bsonType: "string" } }
  } },
  validationLevel: "strict",
  validationAction: "error"
})
db.runCommand({ collMod: "users", validationAction: "warn" })
db.users.renameCollection("members")

Transactions and sessions

JavaScript
const session = db.getMongo().startSession()
session.withTransaction(() => {
  const s = session.getDatabase("shop")
  s.accounts.updateOne({ _id: 1 }, { $inc: { balance: -50 } })
  s.accounts.updateOne({ _id: 2 }, { $inc: { balance: 50 } })
})
session.endSession()

Transactions need a replica set. Prefer single-document atomic updates when your model allows it.

Users, roles and admin

JavaScript
db.createUser({ user: "app", pwd: passwordPrompt(),
                roles: [{ role: "readWrite", db: "shop" }] })
db.getUsers()
db.dropUser("app")
rs.status()                  // replica set state
rs.initiate()                // start a new replica set
sh.status()                  // sharding overview (via mongos)
db.adminCommand({ ping: 1 })
db.serverStatus().connections

Command-line tools

Terminal
mongosh "mongodb://localhost:27017/shop"
mongodump --uri="mongodb://localhost:27017" --db=shop --out=./backup
mongorestore --uri="mongodb://localhost:27017" ./backup
mongoexport --db=shop --collection=products --out=products.json
mongoimport --db=shop --collection=products --file=products.json

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which command updates a specific array element matched by the query filter?

    The positional operator $ refers to the first array element matched by the filter, so "items.$.qty" updates that element's qty.
  2. 2. Which stage should usually come first in a pipeline so it can use an index?

    A leading $match filters early and can use an index; later stages then process fewer documents.
  3. 3. What does { $set: { price: 10 } } do to the other fields of the matched document?

    $set changes only the named fields. replaceOne is the command that swaps the whole document.

Summary

  • CRUD: insertOne/Many, find/findOne, updateOne/Many, replaceOne, deleteOne/Many, bulkWrite.
  • Filters combine implicitly as AND; use $or, $in, $elemMatch and dot notation for the rest.
  • Update with operators ($set, $inc, $push, $pull) rather than rewriting documents.
  • Aggregation is a pipeline: $match early, then $group, $lookup, $project, $sort.
  • Create indexes for your queries (Equality, Sort, Range) and confirm with explain("executionStats").

Back to the beginning of the track with What Is MongoDB? whenever you need to refresh the fundamentals.