MongoDB Cheatsheet
Every essential MongoDB command: database operations, CRUD, query operators, aggregation stages, and indexes, with syntax and real use cases.76 commands · 5 sections
MongoDB is the most popular document database. This cheatsheet covers the operations you write daily: database and collection management, CRUD with find and insert, query operators, the aggregation pipeline, and indexes for performance.
Examples use the mongo/mongosh shell syntax: the same operators work in every driver.
Database & Collection Ops11
use mydbshow dbsshow collectionsdb.createCollection("users")db.dropDatabase()db.getCollectionNames()db.stats()db.users.renameCollection("accounts")db.users.drop()db.runCommand({ ping: 1 })db.version()CRUD Operations22
db.users.insertOne({ name: "Jane", plan: "pro" })db.users.insertMany([{...}, {...}])db.users.find()db.users.findOne({ _id: ObjectId("...") })db.users.find({ plan: "pro" })db.users.find().limit(10)db.users.find().skip(20)db.users.find().sort({ created_at: -1 })db.users.find({}, { name: 1, _id: 0 })db.users.countDocuments({ plan: "pro" })db.users.updateOne({ _id }, { $set: { plan: "pro" } })db.users.updateMany({ plan: "free" }, { $set: { status: "active" } })db.users.updateOne({ _id }, { $inc: { loginCount: 1 } })db.users.updateOne({ _id }, { $push: { tags: "new" } })db.users.updateOne({ _id }, { $pull: { tags: "old" } })db.users.updateOne({ _id }, { $unset: { tempField: "" } })db.users.updateOne({ _id }, { $set: { plan: "pro" } }, { upsert: true })db.users.replaceOne({ _id }, newDoc)db.users.deleteOne({ _id })db.users.deleteMany({ status: "banned" })db.users.deleteMany({})db.users.bulkWrite([...])Query Operators17
db.users.find({ age: { $gt: 30 } })db.users.find({ age: { $gte: 18, $lte: 65 } })db.users.find({ plan: { $in: ["pro", "team"] } })db.users.find({ plan: { $nin: ["banned"] } })db.users.find({ email: { $exists: true } })db.users.find({ email: { $ne: null } })db.users.find({ name: /^ja/i })db.users.find({ $and: [{ plan: "pro" }, { age: { $gt: 18 } }] })db.users.find({ $or: [{ plan: "pro" }, { plan: "team" }] })db.users.find({ tags: "dev" })db.users.find({ tags: { $all: ["dev", "api"] } })db.users.find({ tags: { $size: 3 } })db.users.find({ "address.city": "Berlin" })db.users.find({ $text: { $search: "devvkit" } })db.users.find({ $where: "this.a > this.b" })db.users.find({}, { name: 1 }).toArray().lengthdb.users.findOne({ _id }, { _id: 0, name: 1 })Aggregation Pipeline12
db.orders.aggregate([{ $match: { status: "paid" } }])db.orders.aggregate([{ $group: { _id: "$customer_id", total: { $sum: "$total" } } }])db.orders.aggregate([{ $group: { _id: null, avg: { $avg: "$total" } } }])db.orders.aggregate([{ $sort: { total: -1 } }, { $limit: 5 }])db.orders.aggregate([{ $project: { customer_id: 1, tax: { $multiply: ["$total", 0.1] } } }])db.users.aggregate([{ $unwind: "$tags" }])db.orders.aggregate([{ $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "customer" } }])db.orders.aggregate([{ $group: { _id: "$customer_id", total: { $sum: "$total" } } }, { $match: { total: { $gt: 1000 } } }])db.orders.aggregate([{ $facet: { byStatus: [{ $group: { _id: "$status", n: { $sum: 1 } } }], revenue: [{ $group: { _id: null, sum: { $sum: "$total" } } }] } }])db.events.aggregate([{ $match: { ts: { $gte: start } } }, { $sortByCount: "$event_type" }])db.orders.aggregate([{ $group: { _id: { $dateToString: { format: "%Y-%m", date: "$created_at" } }, total: { $sum: "$total" } } }])db.orders.aggregate([{ $group: { _id: null, total: { $sum: "$total" }, first: { $first: "$_id" }, last: { $last: "$_id" } } }])Indexes & Performance14
db.users.createIndex({ email: 1 })db.users.createIndex({ email: 1 }, { unique: true })db.orders.createIndex({ customer_id: 1, created_at: -1 })db.users.createIndex({ name: "text" })db.sessions.createIndex({ last_seen: 1 }, { expireAfterSeconds: 3600 })db.getCollectionInfos()db.users.getIndexes()db.users.dropIndex("email_1")db.users.explain("executionStats").find({ email: "x@y.com" })db.users.find({ email: "x" }).hint({ email: 1 })db.currentOp()db.killOp(<opid>)db.setProfilingLevel(1, { slowms: 100 })db.system.profile.find().sort({ ts: -1 }).limit(10)MongoDB Cheatsheet
Every essential MongoDB command: database operations, CRUD, query operators, aggregation stages, and indexes, with syntax and real use cases.
MongoDB is the most popular document database. This cheatsheet covers the operations you write daily: database and collection management, CRUD with find and insert, query operators, the aggregation pipeline, and indexes for performance.
Examples use the mongo/mongosh shell syntax: the same operators work in every driver.
Database & Collection Ops
use mydb: Switch to (or create) a database.show dbs: List all databases.show collections: List collections in the current database.db.createCollection("users"): Create an empty collection.db.dropDatabase(): Delete the current database: and everything in it.db.getCollectionNames(): Array of collection names: script-friendly.db.stats(): Database statistics: size, collections, objects.db.users.renameCollection("accounts"): Rename a collection.db.users.drop(): Delete a collection and ALL its documents.db.runCommand({ ping: 1 }): Check server connectivity: the mongo health check.db.version(): Server version: for docs and compatibility.CRUD Operations
db.users.insertOne({ name: "Jane", plan: "pro" }): Insert a single document.db.users.insertMany([{...}, {...}]): Insert many documents in one call.db.users.find(): Return ALL documents in a collection.db.users.findOne({ _id: ObjectId("...") }): Find a single document by id: the lookup pattern.db.users.find({ plan: "pro" }): Find all documents matching a filter.db.users.find().limit(10): Limit results: pagination.db.users.find().skip(20): Skip N documents: page 3.db.users.find().sort({ created_at: -1 }): Sort results: newest first.db.users.find({}, { name: 1, _id: 0 }): Projection: return only specific fields.db.users.countDocuments({ plan: "pro" }): Count matching documents.db.users.updateOne({ _id }, { $set: { plan: "pro" } }): Update ONE document's fields: never overwrite whole docs.db.users.updateMany({ plan: "free" }, { $set: { status: "active" } }): Bulk update all matching documents.db.users.updateOne({ _id }, { $inc: { loginCount: 1 } }): Increment a counter atomically: login stats.db.users.updateOne({ _id }, { $push: { tags: "new" } }): Append to an array field.db.users.updateOne({ _id }, { $pull: { tags: "old" } }): Remove a value from an array.db.users.updateOne({ _id }, { $unset: { tempField: "" } }): Remove a field from a document.db.users.updateOne({ _id }, { $set: { plan: "pro" } }, { upsert: true }): Update or INSERT if missing: idempotent syncs.db.users.replaceOne({ _id }, newDoc): Replace a whole document: new shape, same _id.db.users.deleteOne({ _id }): Delete ONE matching document.db.users.deleteMany({ status: "banned" }): Delete all matching documents.db.users.deleteMany({}): Delete EVERYTHING: collection stays, documents gone.db.users.bulkWrite([...]): Mix inserts/updates/deletes in one batch: fast syncs.Query Operators
db.users.find({ age: { $gt: 30 } }): Greater than: $gte, $lt, $lte for ranges.db.users.find({ age: { $gte: 18, $lte: 65 } }): Range filter: between two values.db.users.find({ plan: { $in: ["pro", "team"] } }): Match any value in a list.db.users.find({ plan: { $nin: ["banned"] } }): Exclude values.db.users.find({ email: { $exists: true } }): Field exists: find docs missing a field.db.users.find({ email: { $ne: null } }): Not null: the mongo null check.db.users.find({ name: /^ja/i }): Regex match: case-insensitive prefix search.db.users.find({ $and: [{ plan: "pro" }, { age: { $gt: 18 } }] }): AND: implicit when fields are separate; explicit for the same field.db.users.find({ $or: [{ plan: "pro" }, { plan: "team" }] }): OR: match either condition.db.users.find({ tags: "dev" }): Array contains: match documents whose array includes the value.db.users.find({ tags: { $all: ["dev", "api"] } }): Array contains ALL values.db.users.find({ tags: { $size: 3 } }): Match arrays with exactly N elements.db.users.find({ "address.city": "Berlin" }): Nested field query: dot notation.db.users.find({ $text: { $search: "devvkit" } }): Full-text search: needs a text index.db.users.find({ $where: "this.a > this.b" }): Compare two fields in the same doc: slow, avoid on big collections.db.users.find({}, { name: 1 }).toArray().length: Count without loading fields: projection + count.db.users.findOne({ _id }, { _id: 0, name: 1 }): Fetch just one field of one doc.Aggregation Pipeline
db.orders.aggregate([{ $match: { status: "paid" } }]): Filter first: always start pipelines with $match.db.orders.aggregate([{ $group: { _id: "$customer_id", total: { $sum: "$total" } } }]): Group and sum: revenue per customer.db.orders.aggregate([{ $group: { _id: null, avg: { $avg: "$total" } } }]): Aggregate over ALL documents: _id: null groups everything.db.orders.aggregate([{ $sort: { total: -1 } }, { $limit: 5 }]): Top 5 orders: sort then limit.db.orders.aggregate([{ $project: { customer_id: 1, tax: { $multiply: ["$total", 0.1] } } }]): Shape output and compute new fields.db.users.aggregate([{ $unwind: "$tags" }]): Flatten arrays into separate documents: per-tag stats.db.orders.aggregate([{ $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "customer" } }]): JOIN: pull related documents from another collection.db.orders.aggregate([{ $group: { _id: "$customer_id", total: { $sum: "$total" } } }, { $match: { total: { $gt: 1000 } } }]): Filter AFTER grouping: $match works at any stage.db.orders.aggregate([{ $facet: { byStatus: [{ $group: { _id: "$status", n: { $sum: 1 } } }], revenue: [{ $group: { _id: null, sum: { $sum: "$total" } } }] } }]): Multiple pipelines in one pass: dashboard queries.db.events.aggregate([{ $match: { ts: { $gte: start } } }, { $sortByCount: "$event_type" }]): Count by value: the group+sort shorthand.db.orders.aggregate([{ $group: { _id: { $dateToString: { format: "%Y-%m", date: "$created_at" } }, total: { $sum: "$total" } } }]): Group by month: time-series revenue.db.orders.aggregate([{ $group: { _id: null, total: { $sum: "$total" }, first: { $first: "$_id" }, last: { $last: "$_id" } } }]): First/last accumulators: oldest and newest docs.Indexes & Performance
db.users.createIndex({ email: 1 }): Single-field index: speed up email lookups.db.users.createIndex({ email: 1 }, { unique: true }): Unique index: enforce no duplicate emails.db.orders.createIndex({ customer_id: 1, created_at: -1 }): Compound index: filter by customer, sort by date.db.users.createIndex({ name: "text" }): Text index: enables $text search.db.sessions.createIndex({ last_seen: 1 }, { expireAfterSeconds: 3600 }): TTL index: auto-delete documents after N seconds. Session expiry.db.getCollectionInfos(): List collections with their indexes.db.users.getIndexes(): Show all indexes on a collection.db.users.dropIndex("email_1"): Drop an index by name.db.users.explain("executionStats").find({ email: "x@y.com" }): Explain: is the query using the index or COLLSCAN?db.users.find({ email: "x" }).hint({ email: 1 }): Force a specific index: temporary query tuning.db.currentOp(): Show running operations: find the slow/hung query.db.killOp(<opid>): Kill a running operation by id.db.setProfilingLevel(1, { slowms: 100 }): Log slow queries: find what to optimize.db.system.profile.find().sort({ ts: -1 }).limit(10): Recent slow queries: the profiler output.Frequently asked questions
What is the difference between find and findOne?
find returns a cursor over all matching documents: you iterate or convert it with .toArray(). findOne returns the first matching document directly, which is convenient for lookups by _id.
How do I update documents?
Use updateOne for a single document, updateMany for all matches, and replaceOne to swap an entire document. Always use update operators like $set, $inc, and $push instead of rewriting whole documents.
What are indexes and when do I need them?
Indexes speed up queries by sorting fields into a searchable structure. Create them on fields used in filters, sorts, and joins (lookups). Use compound indexes for multi-field queries and TTL indexes for expiring data.
What is the aggregation pipeline?
A pipeline processes documents through stages: $match filters, $group aggregates, $project shapes output, $sort orders, and $lookup joins collections. It replaces most multi-step map-reduce logic.