AI Generate MongoDB docs instantly

MongoDB Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

CRUD Operations

4 snippets

Create, read, update, delete

Insert

db.users.insertOne({ name: "Alice", age: 30 });
db.users.insertMany([
  { name: "Bob", age: 25 },
  { name: "Carol", age: 35 },
]);

Find

db.users.find({ age: { $gte: 25 } });
db.users.findOne({ email: "alice@example.com" });
db.users.find({ name: /^A/ }, { name: 1, email: 1, _id: 0 });

Update

db.users.updateOne(
  { _id: ObjectId("...") },
  { $set: { name: "Alice Smith" }, $inc: { loginCount: 1 } }
);
db.users.updateMany(
  { active: false },
  { $set: { archived: true } }
);

Delete

db.users.deleteOne({ _id: ObjectId("...") });
db.users.deleteMany({ lastLogin: { $lt: ISODate("2025-01-01") } });

Query Operators

4 snippets

Comparison, logical, element

Comparison

{ age: { $gt: 25 } }     // greater than
{ age: { $gte: 25 } }    // greater or equal
{ age: { $lt: 30 } }     // less than
{ status: { $in: ["active", "pending"] } }
{ role: { $nin: ["admin"] } }

Logical

{ $and: [{ age: { $gte: 18 } }, { age: { $lte: 65 } }] }
{ $or: [{ status: "active" }, { role: "admin" }] }
{ age: { $not: { $lt: 18 } } }

Element & Regex

{ email: { $exists: true } }
{ score: { $type: "number" } }
{ name: { $regex: /^john/i } }
{ tags: { $size: 3 } }

Array Queries

{ tags: "mongodb" }           // contains element
{ tags: { $all: ["db", "nosql"] } }  // contains all
{ "scores.0": { $gt: 90 } }   // first element > 90
{ results: { $elemMatch: { score: { $gte: 90 }, subject: "math" } } }

Update Operators

2 snippets

Modify documents

Field Updates

{ $set: { name: "New Name" } }
{ $unset: { tempField: "" } }
{ $inc: { views: 1 } }
{ $rename: { "oldName": "newName" } }
{ $mul: { price: 1.1 } }  // multiply by 1.1

Array Updates

{ $push: { tags: "new" } }
{ $push: { scores: { $each: [90, 95], $sort: -1, $slice: 5 } } }
{ $pull: { tags: "removed" } }
{ $addToSet: { tags: "unique" } }
{ $pop: { tags: 1 } }  // remove last

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Aggregation Pipeline

3 snippets

Data processing pipelines

Match & Group

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: {
    _id: "$customerId",
    total: { $sum: "$amount" },
    count: { $sum: 1 },
    avgAmount: { $avg: "$amount" }
  }},
  { $sort: { total: -1 } }
]);

$lookup (JOIN)

{
  $lookup: {
    from: "authors",
    localField: "authorId",
    foreignField: "_id",
    as: "author"
  }
},
{ $unwind: "$author" }

$project

{
  $project: {
    fullName: { $concat: ["$first", " ", "$last"] },
    year: { $year: "$createdAt" },
    isActive: { $cond: { if: { $gte: ["$score", 50] }, then: true, else: false } }
  }
}

Indexes

3 snippets

Query optimization

Create Indexes

db.users.createIndex({ email: 1 }, { unique: true });
db.posts.createIndex({ title: "text", body: "text" });
db.orders.createIndex({ userId: 1, createdAt: -1 });

TTL & Partial

// Auto-delete after 30 days
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 2592000 });
// Only index active users
db.users.createIndex({ email: 1 }, { partialFilterExpression: { active: true } });

Explain

db.users.find({ email: "a@b.com" }).explain("executionStats");
// Check: executionStats.totalDocsExamined vs nReturned
db.users.getIndexes();

Shell Commands

2 snippets

mongosh essentials

Database Ops

show dbs
use mydb
show collections
db.stats()
db.users.stats()
db.users.countDocuments({ active: true })

Backup & Restore

mongodump --db=mydb --out=/backup/
mongorestore --db=mydb /backup/mydb/
mongodump --uri="mongodb+srv://..." --gzip --archive=backup.gz

More Cheat Sheets

FAQ

Frequently asked questions

What is a MongoDB cheat sheet?

A MongoDB cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in MongoDB. It helps developers quickly look up syntax without searching through documentation.

How do I learn MongoDB quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important MongoDB concepts?

Key MongoDB concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my MongoDB code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your MongoDB code using AI.

Related resources

Stop memorizing. Start shipping.

Generate MongoDB Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week