MongoDB Cheat Sheet

A quick reference for MongoDB queries, aggregation, and indexing.

CRUD Operations

Createdb.users.insertOne({ name: 'John', age: 30 })
Create manydb.users.insertMany([{...}, {...}])
Readdb.users.find({ age: { $gt: 18 } })
Read onedb.users.findOne({ email: 'john@example.com' })
Updatedb.users.updateOne({ _id: 1 }, { $set: { name: 'Jane' } })
Deletedb.users.deleteOne({ _id: 1 })
Countdb.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
Projectiondb.users.find({}, { name: 1, email: 1, _id: 0 })

Aggregation Pipeline

$matchFilter documents (like find)
$groupGroup by field: { _id: "$status", count: { $sum: 1 } }
$sort{ $sort: { createdAt: -1 } }
$projectReshape documents (include/exclude fields)
$lookupLeft outer join to another collection
$unwindDeconstruct array field into multiple documents