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
| Operator | Category | Purpose / Example |
|---|---|---|
$eq / $ne | Comparison | { status: { $eq: "A" } } |
$gt / $gte / $lt / $lte | Comparison | { age: { $gte: 18 } } |
$in / $nin | Comparison | { role: { $in: ["admin", "editor"] } } |
$and / $or | Logical | { $or: [{ age: { $lt: 18 } }, { active: false }] } |
$set / $unset | Update | { $set: { email: "new@example.com" } } |
$push / $pull | Array 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 Type | Command Syntax | Description |
|---|---|---|
| Single Field | db.users.createIndex({ email: 1 }) | Index single field ascending (1) or descending (-1) |
| Compound Index | db.orders.createIndex({ customerId: 1, date: -1 }) | Index multiple fields for multi-column queries |
| Text Index | db.articles.createIndex({ title: "text", body: "text" }) | Full-text search index across string fields |
| TTL Index | db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }) | Automatically delete documents after time limit |
Common Pitfalls & Tips
[!WARNING] Mongoose
update()andfindOneAndUpdate()queries do not trigger Mongoose documentsavemiddleware 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.