MongoDB  

MongoDB Cheatsheet: A Complete Guide for Beginners

Introduction

MongoDB is a NoSQL database that stores data in JSON-like documents. It does not use tables and rows like traditional relational databases. Instead, it uses collections and documents, making it flexible, fast, and easy to scale. This cheatsheet will help you learn the basic and most useful MongoDB commands and concepts.

1. Database

Definition: A database is a container for collections.

Example

use myDatabase

Key Point: If the database does not exist, MongoDB creates it when data is inserted.

2. Collection

Definition: A collection is like a table in SQL. It holds multiple documents.

Example

db.createCollection("students")

Key Point: Collections are created automatically when you insert a document.

3. Document

Definition: A document is a JSON-like object that stores data in key-value pairs.

Example

{ name: "Alice", age: 21, course: "Math" }

Key Point: MongoDB documents can have different fields in the same collection.

4. Insert Document

Definition: Add data into a collection.

Example

db.students.insertOne({ name: "John", age: 22 })
db.students.insertMany([
  { name: "Jane", age: 20 },
  { name: "Mark", age: 23 }
])

Key Point: Use insertOne() for a single document and insertMany() for multiple.

5. Find Documents

Definition: Read or query data from a collection.

Example

db.students.find()
db.students.find({ age: 22 })

Key Point: find() without parameters returns all documents.

6. Projection

Definition: Select specific fields from documents.

Example

db.students.find({}, { name: 1, _id: 0 })

Key Point: Use 1 to include a field, 0 to exclude. _id is included by default.

7. Update Document

Definition: Modify existing documents.

Example

db.students.updateOne({ name: "John" }, { $set: { age: 24 } })
db.students.updateMany({}, { $set: { active: true } })

Key Point: Use $set to change values. Use updateMany() to update multiple documents.

8. Delete Document

Definition: Remove documents from a collection.

Example

db.students.deleteOne({ name: "Mark" })
db.students.deleteMany({ age: { $lt: 21 } })

Key Point: deleteOne() removes only the first matching document.

9. Query Operators

Definition: Operators used to filter documents.

Example

db.students.find({ age: { $gt: 20 } })   // Greater than
db.students.find({ age: { $in: [21, 22] } })  // Matches any value in the array

Common Operators

  • $gt: greater than
  • $lt: less than
  • $gte: greater than or equal
  • $lte: less than or equal
  • $ne: not equal
  • $in: in array
  • $nin: not in array

10. Sorting

Definition: Arrange documents in order.

Example

db.students.find().sort({ age: 1 }) // Ascending
db.students.find().sort({ age: -1 }) // Descending

Key Point: Use 1 for ascending, -1 for descending.

11. Limiting Results

Definition: Limit the number of results.

Example

db.students.find().limit(5)

Key Point: Useful for pagination or showing top records.

12. Counting Documents

Definition: Count the number of matching documents.

Example

db.students.countDocuments({ age: 22 })

Key Point: Gives the exact count of documents matching the condition.

13. Indexes

Definition: Improve the speed of search queries.

Example

db.students.createIndex({ name: 1 })

Key Point: Use indexes on frequently searched fields.

14. Aggregation

Definition: Process data and return computed results.

Example

db.students.aggregate([
  { $group: { _id: "$course", total: { $sum: 1 } } }
])

Key Point: Use aggregation for reports, statistics, and complex queries.

15. Renaming Fields

Definition: Change the name of a field.

Example

db.students.updateMany({}, { $rename: { "course": "subject" } })

Key Point: $rename is used only to change field names.

16. Dropping Collection

Definition: Delete an entire collection.

Example

db.students.drop()

Key Point: This deletes all documents in the collection permanently.

17. Dropping Database

Definition: Delete the database completely.

Example

db.dropDatabase()

Key Point: All collections in the database will be deleted.

18. Data Types

Definition: MongoDB supports different types of data.

Common Types

  • String: "Hello"
  • Number: 123
  • Boolean: true or false
  • Date: new Date()
  • Array: [1, 2, 3]
  • Object: { key: value }
  • Null: null

19. Embedded Documents

Definition: Store a document inside another document.

Example

{
  name: "John",
  address: { city: "Delhi", zip: "110001" }
}

Key Point: Useful for related data stored together.

20. MongoDB Shell vs Compass

MongoDB Shell

  • Text-based command-line interface
  • Good for scripting and quick commands

MongoDB Compass

  • Graphical tool
  • Easy to visualize data and collections

21. Upsert (Update or Insert)

Definition: Updates a document if it exists, otherwise inserts it.

Example

db.students.updateOne(
  { name: "Sam" },
  { $set: { age: 25 } },
  { upsert: true }
)

Key Point: Prevents duplicate check-in logic. Saves a step when you want to update or create.

22. $and, $or, $not, $nor Operators

Definition: Combine multiple conditions in queries.

Example

db.students.find({ $and: [ { age: { $gt: 20 } }, { course: "Math" } ] })
db.students.find({ $or: [ { age: 18 }, { course: "Physics" } ] })

Key Point: Use for complex filter conditions.

23. Array Query Operators

Definition: Work with arrays inside documents.

Example

db.students.find({ scores: { $all: [90, 100] } })
db.students.find({ scores: { $elemMatch: { $gt: 90, $lt: 100 } } })

Common Operators

  • $all: matches all values in the array.
  • $size: matches array length.
  • $elemMatch: matches array elements with conditions.

24. $inc, $mul, $min, $max

Definition: Arithmetic operators to update numeric fields.

Example

db.students.updateOne({ name: "Alice" }, { $inc: { age: 1 } })

Key Point: Helps when you need to perform numeric operations directly in update.

25. Text Search

Definition: Perform a full-text search on string fields.

Example

db.articles.createIndex({ content: "text" })
db.articles.find({ $text: { $search: "mongodb tutorial" } })

Key Point: Only works on fields with a text index.

26. Regular Expressions

Definition: Use regex to match patterns in string fields.

Example

db.students.find({ name: { $regex: /^A/, $options: 'i' } })

Key Point: Useful for searching text with flexible matching.

27. Aggregation Stages (Extra)

Common Stages

  • $match: filter documents
  • $group: group by field
  • $sort: sort results
  • $project: reshape documents
  • $limit: restrict output
  • $skip: skip records

Example

db.students.aggregate([
  { $match: { age: { $gte: 20 } } },
  { $group: { _id: "$course", avgAge: { $avg: "$age" } } }
])

Key Point: Aggregation is powerful for reporting and analytics.

28. $lookup (Join in Aggregation)

Definition: Join documents from another collection.

Example

db.orders.aggregate([
  {
    $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customerInfo"
    }
  }
])

Key Point: Emulates SQL JOIN. Useful for merging related data from two collections.

29. Data Validation (Schema Rules)

Definition: Set rules for document structure using validation.

Example

db.createCollection("students", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "age"],
      properties: {
        name: { bsonType: "string" },
        age: { bsonType: "int", minimum: 0 }
      }
    }
  }
})

Key Point: MongoDB is schema-less by default, but validation can enforce rules.

30. ObjectId

Definition: The default unique identifier for MongoDB documents.

Example:

{ "_id": ObjectId("64f1d33ea51d6d92c24a1122") }

Key Point: Each ObjectId includes a timestamp. You can extract creation time using.

ObjectId("64f1d33ea51d6d92c24a1122").getTimestamp()

31. Rename Collection

Definition: Change the name of an existing collection.

Example

db.oldName.renameCollection("newName")

Key Point: Useful during data migration or refactoring.

32. Backup and Restore

Tools

  • mongodump: create backup
  • mongorestore: restore from backup

Example

mongodump --db=myDatabase
mongorestore --db=myDatabase dump/myDatabase

Key Point: Always back up before applying bulk updates or deletes.

33. Transactions (Multi-document)

Definition: Execute multiple operations as a single unit.

Example

const session = db.getMongo().startSession()
session.startTransaction()
try {
  session.getDatabase("shop").products.insertOne({ name: "Phone", stock: 10 })
  session.getDatabase("shop").orders.insertOne({ product: "Phone" })
  session.commitTransaction()
} catch (e) {
  session.abortTransaction()
}

Key Point: Supported in replica sets. Ensures atomic operations across multiple collections.

34. $merge (Aggregation Output)

Definition: Writes aggregation results into a new or existing collection.

Example

db.sales.aggregate([
  { $group: { _id: "$item", total: { $sum: "$price" } } },
  { $merge: "totals" }
])

Key Point: Like a “save as new collection” step in aggregations. Can replace, merge, or keep existing documents.

35. Change Streams

Definition: Listen to real-time changes (insert, update, delete) in collections.

Example (Node.js)

db.collection("students").watch().on("change", data => {
  console.log("Change detected:", data)
})

Key Point: Useful for building real-time applications like dashboards, logs, or notifications.

36. Capped Collections

Definition: Fixed-size collections that automatically overwrite oldest data.

Example

db.createCollection("logs", { capped: true, size: 100000 })

Key Point: Ideal for logs, sensor data, or limited-history feeds.

37. Time-to-Live (TTL) Index

Definition: Automatically deletes documents after a specified time.

Example

db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

Key Point: Good for expiring sessions, tokens, temporary cache, etc.

38. Hidden Replica Set Members

  • Definition: Replica nodes that receive replication but are not queried directly.
  • Example: Set "hidden": true in replica config.
  • Key Point: Used for analytics, backups, and reporting without affecting primary node performance.

39. $out (Aggregation Final Output)

Definition: Replaces an entire collection with aggregation results.

Example

db.orders.aggregate([
  { $group: { _id: "$status", count: { $sum: 1 } } },
  { $out: "status_summary" }
])

Key Point: Destructive. Use when you want to overwrite a collection with processed data.

40. Sharding

Definition: Horizontal scaling of data across multiple servers.

Example: Not code-based but enabled via cluster setup and,

sh.enableSharding("myDatabase")

Key Point: Used for very large-scale systems where single-node scaling is not enough.

41. $cond, $ifNull, and Ternary Logic in Aggregation

Definition: Use conditional logic inside aggregation pipelines.

Example

db.students.aggregate([
  {
    $project: {
      status: {
        $cond: { if: { $gte: ["$marks", 40] }, then: "Pass", else: "Fail" }
      }
    }
  }
])

Key Point: Enables smart calculations and conditional fields in reports or transformations.

42. $facet in Aggregation

Definition: Run multiple aggregations in a single pipeline.

Example

db.products.aggregate([
  {
    $facet: {
      "priceStats": [ { $group: { _id: null, avgPrice: { $avg: "$price" } } } ],
      "categoryCount": [ { $group: { _id: "$category", count: { $sum: 1 } } } ]
    }
  }
])

Key Point: Useful for dashboards, lets you return multiple sets of grouped data at once.

43. GridFS

  • Definition: Stores and retrieves large files (e.g., images, videos) in chunks.
  • Key Point: Used when files exceed 16MB BSON size limit.

44. Field-Level Encryption

  • Definition: Encrypts specific fields in documents at the driver level.
  • Key Point: Ideal for securing sensitive data (e.g., PII, passwords) without encrypting the whole DB.

45. Bulk Write

Definition: Perform multiple write operations in a single command.

Example

db.students.bulkWrite([
  { insertOne: { document: { name: "Tom", age: 22 } } },
  { updateOne: { filter: { name: "Alice" }, update: { $set: { age: 23 } } } },
  { deleteOne: { filter: { name: "Bob" } } }
])

Key Point: Reduces round-trips to the server. Ideal for batch operations.

46. Collation

Definition: Set rules for string comparison (like case-insensitive search).

Example

db.students.find({ name: "john" }).collation({ locale: 'en', strength: 2 })

Key Point: Useful for case-insensitive or locale-aware queries.