MongoDB Cheat Sheet
A quick reference for MongoDB queries, aggregation, and indexing.
CRUD Operations
| Create | db.users.insertOne({ name: 'John', age: 30 }) |
| Create many | db.users.insertMany([{...}, {...}]) |
| Read | db.users.find({ age: { $gt: 18 } }) |
| Read one | db.users.findOne({ email: 'john@example.com' }) |
| Update | db.users.updateOne({ _id: 1 }, { $set: { name: 'Jane' } }) |
| Delete | db.users.deleteOne({ _id: 1 }) |
| Count | db.users.countDocuments({ status: 'active' }) |
Query Operators
| Comparison | $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin |
| Logical | $and, $or, $not, $nor |
| Element | $exists, $type |
| Array | $all, $elemMatch, $size |
| Evaluation | $regex, $expr, $mod |
| Projection | db.users.find({}, { name: 1, email: 1, _id: 0 }) |
Aggregation Pipeline
| $match | Filter documents (like find) |
| $group | Group by field: { _id: "$status", count: { $sum: 1 } } |
| $sort | { $sort: { createdAt: -1 } } |
| $project | Reshape documents (include/exclude fields) |
| $lookup | Left outer join to another collection |
| $unwind | Deconstruct array field into multiple documents |