Skip to content

cheatnotes/mongodb-cheatsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

MongoDB Comprehensive Cheatsheet

Complete MongoDB cheatsheet covering databases, collections, CRUD operations, query/update operators, aggregation pipeline, indexing, data types, performance tuning, and best practices. Includes practical examples for both beginners and advanced developers working with MongoDB.

Table of Contents

  1. Basic Concepts
  2. Installation & Setup
  3. Database Operations
  4. Collection Operations
  5. CRUD Operations
  6. Query Operators
  7. Update Operators
  8. Aggregation Pipeline
  9. Indexing
  10. Data Types
  11. Useful Shell Commands
  12. Performance & Best Practices

1. Basic Concepts

Concept SQL Equivalent Description
Database Database Container for collections
Collection Table Group of documents
Document Row JSON-like record
Field Column Key-value pair
Embedded Document Join (via foreign key) Nested sub-document
Reference Foreign Key Link between collections

2. Installation & Setup

Start MongoDB Server

# Linux/macOS
sudo systemctl start mongod
mongod --dbpath /path/to/data

# Windows (as administrator)
net start MongoDB
mongod --dbpath C:\data\db

# Connection string
mongodb://localhost:27017
mongodb://username:password@host:27017/dbname

Connect to Shell

mongosh                          # Connect to localhost:27017
mongosh "mongodb://localhost:27017"
mongosh --username admin --password pass --host localhost --port 27017

3. Database Operations

// Show all databases
show dbs
show databases

// Create / Switch to database (use creates if doesn't exist)
use myDatabase

// Check current database
db

// Drop current database
db.dropDatabase()

// List databases with size
db.adminCommand('listDatabases')

4. Collection Operations

// Create collection
db.createCollection("users")
db.createCollection("logs", { capped: true, size: 1048576 })  // capped with 1MB max

// Show collections
show collections
db.getCollectionNames()

// Drop collection
db.users.drop()

// Rename collection
db.users.renameCollection("customers")

// Check collection stats
db.users.stats()

// Check if collection is capped
db.users.isCapped()

5. CRUD Operations

Create (Insert)

// Insert single document
db.users.insertOne({
    name: "John Doe",
    email: "john@example.com",
    age: 30,
    status: "active"
})

// Insert multiple documents
db.users.insertMany([
    { name: "Jane", email: "jane@example.com", age: 25 },
    { name: "Bob", email: "bob@example.com", age: 35 }
])

// Insert with custom _id
db.users.insertOne({ _id: 1001, name: "Custom ID", age: 40 })

Read (Query)

// Find all documents
db.users.find()
db.users.find().pretty()     // Formatted output

// Find with filter
db.users.find({ age: 30 })
db.users.find({ age: 30, status: "active" })  // AND condition

// Find one document
db.users.findOne({ name: "John Doe" })

// Projection (select specific fields)
db.users.find({}, { name: 1, email: 1, _id: 0 })  // 1 = include, 0 = exclude

// Limit, Skip, Sort
db.users.find().limit(5)
db.users.find().skip(10)
db.users.find().sort({ age: 1 })      // ascending
db.users.find().sort({ age: -1 })     // descending
db.users.find().sort({ age: -1, name: 1 })

// Count documents
db.users.countDocuments({ age: { $gt: 25 } })
db.users.estimatedDocumentCount()     // Approximate count

Update

// Update one document
db.users.updateOne(
    { name: "John Doe" },           // Filter
    { $set: { age: 31, status: "inactive" } }
)

// Update multiple documents
db.users.updateMany(
    { status: "active" },
    { $set: { lastLogin: new Date() } }
)

// Replace entire document
db.users.replaceOne(
    { name: "John Doe" },
    { name: "John Smith", email: "john.smith@example.com", age: 32 }
)

// Upsert (insert if doesn't exist)
db.users.updateOne(
    { email: "new@example.com" },
    { $set: { name: "New User", created: new Date() } },
    { upsert: true }
)

Delete

// Delete one document
db.users.deleteOne({ name: "John Doe" })

// Delete multiple documents
db.users.deleteMany({ status: "inactive" })

// Delete all documents
db.users.deleteMany({})

// Find and delete (returns deleted document)
db.users.findOneAndDelete({ age: { $lt: 18 } })

6. Query Operators

Comparison Operators

Operator Meaning
$eq Equal to
$ne Not equal to
$gt Greater than
$gte Greater than or equal to
$lt Less than
$lte Less than or equal to
$in In array
$nin Not in array
db.users.find({ age: { $gt: 25, $lt: 50 } })
db.users.find({ status: { $in: ["active", "pending"] } })
db.users.find({ age: { $ne: 30 } })

Logical Operators

Operator Meaning
$and All conditions true
$or At least one condition true
$nor None of the conditions true
$not Negates condition
db.users.find({ $or: [{ age: { $lt: 20 } }, { age: { $gt: 60 } }] })
db.users.find({ $and: [{ age: { $gte: 18 } }, { status: "active" }] })
db.users.find({ $nor: [{ status: "inactive" }, { age: { $lt: 18 } }] })

Element Operators

db.users.find({ email: { $exists: true } })      // Field exists
db.users.find({ phone: { $type: "string" } })    // Field type
db.users.find({ age: { $type: "number" } })

Evaluation Operators

// Regular expression
db.users.find({ name: { $regex: /^John/i } })
db.users.find({ email: { $regex: /@gmail\.com$/ } })

// Where (JavaScript expression - use rarely, slower)
db.users.find({ $where: "this.age > 30" })

// Modulo
db.users.find({ age: { $mod: [5, 0] } })  // age divisible by 5

Array Operators

// Array with specific element
db.users.find({ tags: "premium" })

// Match all elements in array
db.users.find({ tags: { $all: ["premium", "verified"] } })

// Array size
db.users.find({ tags: { $size: 3 } })

// Element match
db.users.find({ 
    scores: { $elemMatch: { $gte: 80, $lte: 90 } }
})

// Match by index position
db.users.find({ "tags.0": "admin" })

7. Update Operators

Field Operators

Operator Description
$set Set field value
$unset Remove field
$inc Increment field (numeric)
$mul Multiply field
$rename Rename field
$min Update if new value is lower
$max Update if new value is higher
$currentDate Set to current date
db.users.updateOne(
    { name: "John" },
    { 
        $set: { city: "New York" },
        $inc: { loginCount: 1 },
        $rename: { "phone": "contactNumber" },
        $currentDate: { lastModified: true }
    }
)

Array Update Operators

// Add element to array
db.users.updateOne(
    { name: "John" },
    { $push: { tags: "new-tag" } }
)

// Add multiple elements
db.users.updateOne(
    { name: "John" },
    { $push: { tags: { $each: ["tag1", "tag2"] } } }
)

// Add to array with ordering/slicing
db.users.updateOne(
    { name: "John" },
    { 
        $push: { 
            logs: { 
                $each: ["new log"], 
                $slice: -10,   // Keep last 10
                $sort: -1      // Sort descending
            } 
        } 
    }
)

// Remove elements
db.users.updateOne(
    { name: "John" },
    { $pop: { tags: 1 } }       // Remove last element
)

db.users.updateOne(
    { name: "John" },
    { $pop: { tags: -1 } }      // Remove first element
)

db.users.updateOne(
    { name: "John" },
    { $pull: { tags: "old-tag" } }  // Remove specific value
)

db.users.updateOne(
    { name: "John" },
    { $pullAll: { tags: ["tag1", "tag2"] } }  // Remove multiple
)

// Update specific array element
db.users.updateOne(
    { name: "John", "tags.tagName": "old" },
    { $set: { "tags.$.tagName": "new" } }  // $ is positional operator
)

8. Aggregation Pipeline

Stages

db.users.aggregate([
    { $match: { status: "active" } },           // Filter documents
    { $group: { _id: "$city", count: { $sum: 1 } } }, // Group by city
    { $sort: { count: -1 } },                   // Sort by count desc
    { $limit: 5 },                              // Top 5 cities
    { $project: { city: "$_id", count: 1, _id: 0 } }, // Reshape output
    { $unwind: "$tags" },                       // Deconstruct array
    { $lookup: {                                 // Join with another collection
        from: "orders",
        localField: "_id",
        foreignField: "userId",
        as: "userOrders"
    }},
    { $addFields: { fullName: { $concat: ["$firstName", " ", "$lastName"] } } },
    { $out: "active_users_report" }             // Output to collection
])

Common Expressions

// Mathematical
{ $sum: "$age" }           // Sum
{ $avg: "$age" }           // Average
{ $min: "$age" }           // Minimum
{ $max: "$age" }           // Maximum
{ $multiply: ["$price", "$quantity"] }
{ $divide: ["$total", "$count"] }

// String
{ $concat: ["$first", " ", "$last"] }
{ $toUpper: "$name" }
{ $toLower: "$name" }
{ $substr: ["$phone", 0, 3] }
{ $strLenCP: "$name" }

// Conditional
{ $cond: { if: { $gte: ["$age", 18] }, then: "Adult", else: "Minor" } }
{ $ifNull: ["$phone", "No phone"] }
{ $switch: { branches: [...] } }

// Date
{ $year: "$createdAt" }
{ $month: "$createdAt" }
{ $dayOfMonth: "$createdAt" }
{ $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }

// Array
{ $size: "$tags" }
{ $arrayElemAt: ["$items", 0] }
{ $filter: { input: "$items", as: "item", cond: { $gte: ["$$item.price", 100] } } }
{ $map: { input: "$items", as: "item", in: { $multiply: ["$$item.price", 1.1] } } }

9. Indexing

// Create indexes
db.users.createIndex({ email: 1 })                    // Single field (ascending)
db.users.createIndex({ age: -1 })                     // Descending
db.users.createIndex({ name: 1, age: -1 })            // Compound index
db.users.createIndex({ tags: 1 })                     // Array field (multikey)
db.users.createIndex({ email: 1 }, { unique: true })  // Unique index
db.users.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })  // TTL index
db.users.createIndex({ location: "2dsphere" })        // Geospatial index
db.users.createIndex({ name: "text", description: "text" })  // Text index

// Text search
db.users.find({ $text: { $search: "john doe" } })
db.users.find({ $text: { $search: "\"exact phrase\"" } })

// List indexes
db.users.getIndexes()

// Drop index
db.users.dropIndex("email_1")
db.users.dropIndexes()  // Drop all indexes except _id

// Index options
db.users.createIndex(
    { email: 1 },
    { 
        unique: true,
        sparse: true,      // Skip documents missing field
        background: true,  // Build in background
        name: "email_unique_idx"
    }
)

10. Data Types

Type Example
Double { price: 19.99 }
String { name: "John" }
Object { address: { city: "NYC" } }
Array { tags: ["a", "b"] }
Binary data { file: BinData(0, "base64...") }
ObjectId { _id: ObjectId("507f1f77bcf86cd799439011") }
Boolean { active: true }
Date { created: new Date() }
Null { deletedAt: null }
Regular Expression { pattern: /^abc/i }
Integer (32-bit) { count: NumberInt(42) }
Long (64-bit) { bigNum: NumberLong(9999999999) }
Decimal (128-bit) { exact: NumberDecimal("10.99") }

11. Useful Shell Commands

// General
help                                           // MongoDB help
db.help()                                      // Database methods help
db.collection.help()                          // Collection methods help

// Stats & Info
db.stats()                                     // Database stats
db.serverStatus()                              // Server status
db.currentOp()                                 // Current operations
db.killOp(<opId>)                              // Kill operation

// Bulk operations
var bulk = db.users.initializeUnorderedBulkOp()
bulk.insert({ name: "User1" })
bulk.find({ name: "User2" }).update({ $set: { status: "active" } })
bulk.execute()

// Export/Import data
// Terminal commands:
// mongoexport --db mydb --collection users --out users.json
// mongoimport --db mydb --collection users --file users.json
// mongodump --db mydb --out backup/
// mongorestore --db mydb backup/mydb/

// Explain plan
db.users.find({ age: { $gt: 25 } }).explain("executionStats")

// Validate collection
db.users.validate({ full: true })

12. Performance & Best Practices

Schema Design

  1. Embed for "contains" relationships (one-to-few)
  2. Reference for "many" relationships (one-to-many/many-to-many)
  3. Avoid unbounded arrays (use referencing instead)
  4. Design for application query patterns

Query Optimization

// Use covered queries
db.users.createIndex({ status: 1, age: 1 })
db.users.find({ status: "active" }, { status: 1, age: 1, _id: 0 })

// Use projection to limit returned fields
db.users.find({}, { password: 0 })  // Exclude password

// Use limit for pagination
db.users.find().skip(100).limit(20)  // Avoid large skips, use range queries instead

// Prefer $in over multiple $or conditions
// Good:
db.users.find({ status: { $in: ["active", "pending"] } })
// Avoid:
db.users.find({ $or: [{ status: "active" }, { status: "pending" }] })

Indexing Tips

  1. Create indexes for frequently queried fields
  2. Order matters in compound indexes (equality → sort → range)
  3. Use sparse indexes for optional fields
  4. Avoid indexes with high write load
  5. Monitor index usage with db.collection.aggregate([{ $indexStats: {} }])

Write Concerns & Read Preferences

// Write concern
db.users.insertOne({ name: "John" }, { writeConcern: { w: "majority", wtimeout: 5000 } })

// Read preference
db.users.find().readPref("secondaryPreferred")  // primary, secondary, nearest, etc.

Monitoring

// Enable profiling for slow queries
db.setProfilingLevel(2)  // 0=off, 1=slow (>100ms), 2=all
db.setProfilingLevel(1, { slowms: 50 })

// View profile data
db.system.profile.find().pretty()

// Check current queries
db.currentOp({ "active": true })

// Check indexes used
db.collection.aggregate([{ $indexStats: {} }])

About

Complete MongoDB cheatsheet covering databases, collections, CRUD operations, query/update operators, aggregation pipeline, indexing, data types, performance tuning, and best practices. Includes practical examples for both beginners and advanced developers working with MongoDB.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Generated from cheatnotes/cheatnotes