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
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
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 |
|
Insert many |
|
Find all |
|
Find one |
|
Find + projection |
|
Update one |
|
Update many |
|
Upsert |
|
Replace |
|
Delete one |
|
Delete many |
|
Count |
|
Query Operators
Operator | Meaning |
|---|---|
| Equal / not equal |
| Greater than / greater or equal |
| Less than / less or equal |
| In / not in array of values |
| Logical combinators |
| Negate a condition |
| Field is present (or absent) |
| Field matches a BSON type |
| Pattern match on a string field |
| Array contains all listed values |
| Array element matches multiple conditions at once |
| Array has an exact length |
Update Operators
Operator | Meaning |
|---|---|
| Set a field’s value |
| Remove a field |
| Increment/decrement a number |
| Multiply a number |
| Rename a field |
| Append to an array |
| Append to an array only if not already present |
| Remove matching elements from an array |
| Remove first (-1) or last (1) array element |
| Set only if new value is smaller/larger |
| Set a field to the current date |
Aggregation Pipeline Stages
Stage | Purpose |
|---|---|
| Filter documents (like find()) |
| Reshape documents / include-exclude fields |
| Group by key and compute aggregates |
| Sort documents |
| Pagination |
| Flatten an array field into one document per element |
| Left outer join to another collection |
| Count documents passing through the pipeline |
| Run multiple sub-pipelines in parallel, e.g. results + total count |
| Group into ranges/buckets |
| Add computed fields without dropping existing ones |
| Promote a sub-document to be the new root document |
| Write pipeline results to a collection |
db.orders.aggregate([
{ $match: { status: "shipped" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" }, count: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 10 }
])Index Commands
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 usageAdmin & Diagnostics
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)
# 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 results |
| Cap number of documents returned |
| Skip the first n documents |
| Count matching documents (deprecated — use countDocuments) |
| Materialize the cursor into an array |
| Iterate each document |
| 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.