MongoDB Cheat Sheet
Shell basics
// databases and collections
show dbs; use school; show collections; db.dropDatabase()
db.createCollection("logs"); db.logs.drop()
CRUD
db.c.insertOne({ name: "A" }); db.c.insertMany([{ a: 1 }, { a: 2 }])
db.c.find({ age: { $gte: 18 } }, { name: 1, _id: 0 }).sort({ age: -1 }).skip(10).limit(5)
db.c.findOne({ _id: id }); db.c.countDocuments({ city: "Pune" }); db.c.distinct("city")
db.c.updateOne({ _id: id }, { $set: { a: 1 }, $inc: { n: 1 } }); db.c.updateMany(f, { $unset: { tmp: "" } })
db.c.updateOne(f, { $push: { tags: "x" } }, { upsert: true }); db.c.replaceOne(f, doc)
db.c.deleteOne({ _id: id }); db.c.deleteMany({ done: true })
Query operators
{ a: { $in: [1, 2] } }; { a: { $exists: true } }; { $or: [{ a: 1 }, { b: 2 }] }
{ tags: "js" }; { tags: { $all: ["a", "b"] } }; { items: { $elemMatch: { qty: { $gt: 5 } } } }
{ "address.city": "Pune" }; { name: { $regex: "^a", $options: "i" } }
Aggregation
db.c.aggregate([{ $match: {} }, { $group: { _id: "$city", n: { $sum: 1 }, avg: { $avg: "$m" } } }, { $sort: { n: -1 } }])
{ $project: { name: 1, total: { $add: ["$a", "$b"] } } }; { $unwind: "$tags" }; { $limit: 10 }
{ $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }
Indexes
db.c.createIndex({ city: 1, marks: -1 }); db.c.createIndex({ email: 1 }, { unique: true })
db.c.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }); db.c.getIndexes()
db.c.find(f).explain("executionStats")
Mongoose
const User = mongoose.model("User", new mongoose.Schema({ name: { type: String, required: true } }, { timestamps: true }));
await User.create(doc); await User.find(f).select("name").sort({ createdAt: -1 }).limit(10).lean();
await User.findById(id).populate("posts"); await User.findByIdAndUpdate(id, { $set: d }, { new: true });
Full MongoDB documentation