⚡ 100% In-Browser & Private: Your data never leaves your computer. Powered by Cloudflare Edge CDN.
ProWebTools PRO
Developer & SEO Utilities
30+ Commands

MongoDB & Mongosh Queries Cheat Sheet

Production MongoDB command cheat sheet: find filters ($in, $gte), projections, updateOne ($set), aggregation pipelines ($match, $group), and unique indexes with 1-click copy.

Database & Shell (5 commands)

Database & Shell
mongosh "mongodb://localhost:27017/mydb"

Connects to a local MongoDB instance using the modern MongoDB Shell (mongosh).

PRO TIP Pass --username and --password for authenticated instances.
Database & Shell
show dbs

Lists all databases and their disk storage sizes on the connected cluster.

PRO TIP Databases without collections and documents are omitted from the list.
Database & Shell
use <database_name>

Switches the current active database context. Creates database upon first insert.

PRO TIP Type "db" to verify the current active database context.
Database & Shell
show collections

Displays all collections (tables) present within the currently selected database.

PRO TIP Equivalent to db.getCollectionNames().
Database & Shell
db.stats()

Displays storage statistics, index sizes, data size, and document count for the database.

PRO TIP Pass { scale: 1024 * 1024 } for megabyte formatting.

CRUD: Read Queries (5 commands)

CRUD: Read Queries
db.users.find()

Retrieves all documents from the users collection with default batch pagination.

PRO TIP Add .pretty() in legacy mongo shell or .limit(20) to constrain result set.
CRUD: Read Queries
db.users.find({ status: "active" }, { name: 1, email: 1, _id: 0 })

Queries documents with projection, returning only name and email fields without _id.

PRO TIP Projections substantially reduce network bandwidth and memory overhead.
CRUD: Read Queries
db.users.find({ age: { $gte: 21, $lte: 65 } })

Filters documents using range comparison operators ($gte, $lte, $gt, $lt, $ne).

PRO TIP Combine with compound indexes for instantaneous range scan lookups.
CRUD: Read Queries
db.users.find({ role: { $in: ["admin", "editor"] } })

Matches documents where the field value matches any element in the specified array.

PRO TIP Use $nin for inverse (not-in) filtering.
CRUD: Read Queries
db.users.find({ "address.city": "San Francisco" })

Queries nested sub-documents and embedded objects using dot notation.

PRO TIP Dot notation requires field names to be wrapped in quotes.

CRUD: Write & Update (5 commands)

CRUD: Write & Update
db.users.insertOne({ name: "Alice", email: "[email protected]", createdAt: new Date() })

Inserts a single document and returns the newly generated ObjectId _id.

PRO TIP Use insertMany([...]) for bulk document ingestion.
CRUD: Write & Update
db.users.updateOne({ _id: ObjectId("...") }, { $set: { status: "verified" } })

Updates specified fields in a single document matching the filter criteria.

PRO TIP Always use $set to avoid accidentally overwriting the entire document object.
CRUD: Write & Update
db.users.updateMany({ active: false }, { $set: { archived: true } })

Updates all documents matching the query filter in a single atomic operation.

PRO TIP Returns acknowledged count and modifiedCount in the operation receipt.
CRUD: Write & Update
db.users.updateOne({ email: "[email protected]" }, { $set: { loginCount: 1 } }, { upsert: true })

Performs an UPSERT: inserts a new document if no matching record is found.

PRO TIP Eliminates race conditions when initializing tracking or counter records.
CRUD: Write & Update
db.users.deleteOne({ _id: ObjectId("...") })

Deletes a single document matching the specified criteria.

PRO TIP Use deleteMany({}) to purge all documents while preserving collection indexes.

Indexes & Profiling (4 commands)

Indexes & Profiling
db.users.createIndex({ email: 1 }, { unique: true })

Creates an ascending single-field unique index enforcing zero duplicate emails.

PRO TIP Unique indexes prevent duplicate race conditions at the database engine level.
Indexes & Profiling
db.orders.createIndex({ customerId: 1, createdAt: -1 })

Creates a compound index supporting queries filtered by customer and sorted by date.

PRO TIP Follow the ESR rule (Equality, Sort, Range) when ordering compound index keys.
Indexes & Profiling
db.users.getIndexes()

Lists all indexes configured on the collection, including sizes and build versions.

PRO TIP Check for unutilized or redundant indexes consuming excess write IOPS.
Indexes & Profiling
db.users.find({ email: "[email protected]" }).explain("executionStats")

Analyzes query execution plans, index scans (IXSCAN) vs collection scans (COLLSCAN).

PRO TIP Look for totalDocsExamined vs nReturned; ideally they should match closely.

Aggregations & Backup (2 commands)

Aggregations & Backup
db.orders.aggregate([{ $match: { status: "completed" } }, { $group: { _id: "$customerId", total: { $sum: "$amount" } } }])

Executes an aggregation pipeline filtering orders and computing total revenue per user.

PRO TIP Ensure the first $match stage uses an index to filter documents early in the pipeline.
Aggregations & Backup
mongodump --uri="mongodb://localhost:27017/mydb" --out=/backup/$(date +%F)

Creates a BSON dump archive of the database for snapshot backups.

PRO TIP Restore dumped backups using mongorestore --uri="..." /backup/path.