Basic CRUD Operations
Insert
db.users.insertOne({ name: "Alice", age: 25 }) / db.users.insertMany([{ name: "Bob" }, { name: "Charlie", age: 30 }])
Read
db.users.find({ age: { $gt: 20 } },{ name: 1, _id: 0 }) ) .distinct() .count() sort({ age: -1 }).limit(5).skip(10)
Update
db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } })
db.example.updateOne( { _id: 1 },{
Basic Field Updates
$set: { name: "Alice", age: 30 },
$unset: { tempField: "" },
$rename: { oldName: "newName" },
$inc: { score: 5 },
$mul: { price: 1.2 },
Array Modifiers
$push: { logs: { $each: ["log1", "log2"] } },
$addToSet: { tags: { $each: ["mongodb", "cheatsheet"] } },
$pull: { tags: "outdated" },
$pop: { tags: 1 }, // remove last element
Delete
db.users.deleteOne({ name: "Alice" }) / db.users.deleteMany({ age: { $gte: 30 } })
Query Operators
Comparison
$eq, $ne, $gt, $gte, $lt, $lte, $in, $nin
db.users.find({ age: { $gte: 18, $lte: 30 } })
Logical
$and, $or, $not, $nor
db.users.find({ $or: [{ age: {$lt : 18 } , { name : "Bob" } ] })
Element
db.users.find({ email: { $exists: true } })
db.users.find({ age: { $type: "int" } })
Array
db.posts.find({ tags: { $all: ["tech", "mongodb"] } })
db.posts.find({ tags: { $in: ["ai", "web"] } })
db.posts.find({ comments: { $size: 3 } })
Regex
db.users.find({ name: /ali/i }) // case-insensitive
Aggregation Pipeline
db.authors.aggregate([
{ $project: { name: 1, numberOfAwards : { $size: "$awards" }}}])
db.books.aggregate([
{ $lookup: { from: "authors", localField: "authorId", foreignField: "_id", as: "authorDetails"} },
{ $unwind: "$authorDetails" },
{ $project: { title: 1, authorName: "$authorDetails.name" }
} ])
db.books.aggregate([
{ $group: { _id: "$authorId", totalBooks: { $sum: 1 }, avgRevenue: { $avg: "$price" }, titles : { $push: "$title" }}},
{ $project: { totalBooks: 1, totalRevenue: 1, titles: 1, uniqueTitles: { $size: { $setUnion: ["$titles", []] } } } } ])