MongoDBMongoDB Cheat Sheet

MongoDB / mongosh Cheat Sheet

A single-page quick reference for the commands, operators, and stages you reach for most often in mongosh. Bookmark this page — it's meant for lookup, not linear reading.

Connection

Bash
mongosh                                    # connect to localhost:27017
mongosh "mongodb://localhost:27017/shop"    # connect to a specific database
mongosh "mongodb+srv://user:pass@cluster0.mongodb.net/shop"  # Atlas

JS
show dbs                 // list databases
use shop                  // switch/create database
show collections          // list collections in current db
db.dropDatabase()         // delete current database
CRUD Quick Reference

Operation

Command

Insert one

db.col.insertOne({ a: 1 })

Insert many

db.col.insertMany([{ a: 1 }, { a: 2 }])

Find all

db.col.find()

Find one

db.col.findOne({ a: 1 })

Find + projection

db.col.find({ a: 1 }, { a: 1, _id: 0 })

Update one

db.col.updateOne({ a: 1 }, { $set: { b: 2 } })

Update many

db.col.updateMany({ a: 1 }, { $set: { b: 2 } })

Upsert

db.col.updateOne({ a: 1 }, { $set: { b: 2 } }, { upsert: true })

Replace

db.col.replaceOne({ a: 1 }, { a: 1, b: 2 })

Delete one

db.col.deleteOne({ a: 1 })

Delete many

db.col.deleteMany({ a: 1 })

Count

db.col.countDocuments({ a: 1 })

Query Operators

Operator

Meaning

$eq / $ne

Equal / not equal

$gt / $gte

Greater than / greater or equal

$lt / $lte

Less than / less or equal

$in / $nin

In / not in array of values

$and / $or / $nor

Logical combinators

$not

Negate a condition

$exists

Field is present (or absent)

$type

Field matches a BSON type

$regex

Pattern match on a string field

$all

Array contains all listed values

$elemMatch

Array element matches multiple conditions at once

$size

Array has an exact length

Update Operators

Operator

Meaning

$set

Set a field’s value

$unset

Remove a field

$inc

Increment/decrement a number

$mul

Multiply a number

$rename

Rename a field

$push

Append to an array

$addToSet

Append to an array only if not already present

$pull

Remove matching elements from an array

$pop

Remove first (-1) or last (1) array element

$min / $max

Set only if new value is smaller/larger

$currentDate

Set a field to the current date

Aggregation Pipeline Stages

Stage

Purpose

$match

Filter documents (like find())

$project

Reshape documents / include-exclude fields

$group

Group by key and compute aggregates

$sort

Sort documents

$limit / $skip

Pagination

$unwind

Flatten an array field into one document per element

$lookup

Left outer join to another collection

$count

Count documents passing through the pipeline

$facet

Run multiple sub-pipelines in parallel, e.g. results + total count

$bucket / $bucketAuto

Group into ranges/buckets

$addFields / $set

Add computed fields without dropping existing ones

$replaceRoot

Promote a sub-document to be the new root document

$out / $merge

Write pipeline results to a collection

JS
db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $group: { _id: "$customerId", total: { $sum: "$amount" }, count: { $sum: 1 } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
])
Index Commands

JS
db.col.createIndex({ field: 1 })                          // ascending
db.col.createIndex({ field: -1 })                         // descending
db.col.createIndex({ a: 1, b: -1 })                        // compound
db.col.createIndex({ email: 1 }, { unique: true })          // unique
db.col.createIndex({ location: "2dsphere" })                // geospatial
db.col.createIndex({ title: "text", body: "text" })          // text
db.col.getIndexes()                                          // list indexes
db.col.dropIndex("field_1")                                  // drop by name
db.col.find({ field: 1 }).explain("executionStats")           // check plan usage
Admin & Diagnostics

JS
db.stats()                       // database storage stats
db.col.stats()                    // collection storage stats
db.currentOp()                    // currently running operations
db.serverStatus()                 // server-wide runtime metrics
db.col.totalIndexSize()           // total size of all indexes on collection
db.killOp(opId)                   // kill a running operation by opid
rs.status()                       // replica set status
sh.status()                       // sharding status
Import / Export Tools (Shell, Not mongosh)

Bash
# BSON dump/restore — preserves all types exactly
mongodump --db=shop --out=./backup
mongorestore --db=shop ./backup/shop

# JSON/CSV — human readable, loses some BSON type fidelity
mongoexport --db=shop --collection=users --out=users.json
mongoimport --db=shop --collection=users --file=users.json

# CSV variants
mongoexport --db=shop --collection=users --type=csv --fields=name,email --out=users.csv
mongoimport --db=shop --collection=users --type=csv --headerline --file=users.csv
Cursor Methods

Method

Purpose

.sort({ field: 1 })

Sort results

.limit(n)

Cap number of documents returned

.skip(n)

Skip the first n documents

.count()

Count matching documents (deprecated — use countDocuments)

.toArray()

Materialize the cursor into an array

.forEach(fn)

Iterate each document

.pretty()

Pretty-print output in the shell

Useful mongosh Shortcuts
  • db.col.find().pretty() — readable multi-line output for exploring documents.

  • it — continue iterating a cursor that printed a partial batch.

  • load("script.js") — run a local JS file inside the current shell session.

  • .help() — context-sensitive help, works on db, db.col, and cursors.

  • DBQuery.shellBatchSize = 50 — change how many documents print per page.

Note
This page intentionally favors breadth over explanation — for the reasoning behind any of these (why ESR ordering matters for compound indexes, when to use $facet, etc.) see the dedicated pages under Indexes and Aggregation.