MongoDB & Mongoose Cheat Sheet

Quick reference guide for MongoDB: Aggregation pipeline, CRUD operations, indexing, and Mongoose schemas.

Databases
mongodb
mongoose
nosql

MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like BSON documents. Mongoose provides a straight-forward, schema-based solution to model application data in Node.js.

CRUD Query Operators

Table
OperatorCategoryPurpose / Example
$eq / $neComparison{ status: { $eq: "A" } }
$gt / $gte / $lt / $lteComparison{ age: { $gte: 18 } }
$in / $ninComparison{ role: { $in: ["admin", "editor"] } }
$and / $orLogical{ $or: [{ age: { $lt: 18 } }, { active: false }] }
$set / $unsetUpdate{ $set: { email: "new@example.com" } }
$push / $pullArray Update{ $push: { tags: "developer" } }

Aggregation Pipeline Stages

Aggregation pipelines process documents sequentially through stages.

javascript
db.orders.aggregate([
  // Stage 1: Filter active orders
  { $match: { status: "completed" } },

  // Stage 2: Group by customer and compute total
  {
    $group: {
      _id: "$customerId",
      totalSpent: { $sum: "$amount" },
      count: { $sum: 1 }
    }
  },

  // Stage 3: Join with customers collection ($lookup)
  {
    $lookup: {
      from: "customers",
      localField: "_id",
      foreignField: "_id",
      as: "customerDetails"
    }
  },

  // Stage 4: Sort by totalSpent descending
  { $sort: { totalSpent: -1 } }
]);

Mongoose Schema & Model Example

typescript
import mongoose, { Schema, Document } from "mongoose";

export interface IUser extends Document {
  name: string;
  email: string;
  age?: number;
  roles: string[];
}

const UserSchema: Schema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true, index: true },
  age: { type: Number, min: 0 },
  roles: { type: [String], default: ["user"] }
}, { timestamps: true });

export const User = mongoose.model<IUser>("User", UserSchema);

Indexing & Performance

Table
Index TypeCommand SyntaxDescription
Single Fielddb.users.createIndex({ email: 1 })Index single field ascending (1) or descending (-1)
Compound Indexdb.orders.createIndex({ customerId: 1, date: -1 })Index multiple fields for multi-column queries
Text Indexdb.articles.createIndex({ title: "text", body: "text" })Full-text search index across string fields
TTL Indexdb.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })Automatically delete documents after time limit

Common Pitfalls & Tips

[!WARNING] Mongoose update() and findOneAndUpdate() queries do not trigger Mongoose document save middleware hooks (pre('save')) by default!

[!TIP] Use .lean() in Mongoose queries (e.g., User.find().lean()) when you only need read-only plain JavaScript objects to reduce memory usage and speed up execution.