Tags: mongodb, mongoose, aggregation, indexing, embedded, nosql, database Last updated: 2026-06-26

MongoDB / Mongoose Cheatsheet

Quick Reference

ConceptExample
Finddb.c.find({ status: "active" })
Insertdb.c.insertOne({ name: "Max" })
UpdateupdateOne({}, { $set: {} })
DeletedeleteOne({ _id: id })
Aggregationdb.c.aggregate([...])
IndexcreateIndex({ email: 1 })
Mongoose modelmongoose.model("User", s)
Populatefind().populate("user")

CRUD (MongoDB Shell)

// Insert
db.users.insertOne({ name: "Max", email: "[email protected]" });

// Find
db.users.find({ status: "active" }).limit(10).sort({ name: 1 });

// Update
db.users.updateOne({ _id: ObjectId("...") }, { $set: { name: "Max" } });

// Delete
db.users.deleteOne({ _id: id });

Aggregation Pipeline

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } },
  { $unwind: "$user" },
  { $group: { _id: "$user._id", total: { $sum: "$total" }, count: { $sum: 1 } } },
  { $sort: { total: -1 } },
  { $limit: 10 },
]);

Indexing

// Single, compound, unique, TTL, text
db.users.createIndex({ email: 1 });
db.orders.createIndex({ userId: 1, createdAt: -1 });
db.users.createIndex({ email: 1 }, { unique: true });
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });

// Explain
db.users.find({ email: "[email protected]" }).explain("executionStats");

Embedded vs Referenced

RelationshipPattern
1:1 or 1:fewEmbed
1:many (unbounded)Reference (parent ref)
Many:manyReference (both sides)

Mongoose

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, unique: true },
  posts: [{ type: ObjectId, ref: "Post" }],
});

userSchema.pre("save", function (next) {
  this.updatedAt = new Date(); next();
});

const User = mongoose.model("User", userSchema);

// Queries
const users = await User.find().sort("-createdAt").limit(10);
const user = await User.findByIdAndUpdate(id, { name: "Max" }, { new: true });

Tips