CRUD Operations
4 snippetsCreate, read, update, delete
Insert
db.users.insertOne({ name: "Alice", age: 30 });
db.users.insertMany([
{ name: "Bob", age: 25 },
{ name: "Carol", age: 35 },
]); Find
db.users.find({ age: { $gte: 25 } });
db.users.findOne({ email: "alice@example.com" });
db.users.find({ name: /^A/ }, { name: 1, email: 1, _id: 0 }); Update
db.users.updateOne(
{ _id: ObjectId("...") },
{ $set: { name: "Alice Smith" }, $inc: { loginCount: 1 } }
);
db.users.updateMany(
{ active: false },
{ $set: { archived: true } }
); Delete
db.users.deleteOne({ _id: ObjectId("...") });
db.users.deleteMany({ lastLogin: { $lt: ISODate("2025-01-01") } }); Query Operators
4 snippetsComparison, logical, element
Comparison
{ age: { $gt: 25 } } // greater than
{ age: { $gte: 25 } } // greater or equal
{ age: { $lt: 30 } } // less than
{ status: { $in: ["active", "pending"] } }
{ role: { $nin: ["admin"] } } Logical
{ $and: [{ age: { $gte: 18 } }, { age: { $lte: 65 } }] }
{ $or: [{ status: "active" }, { role: "admin" }] }
{ age: { $not: { $lt: 18 } } } Element & Regex
{ email: { $exists: true } }
{ score: { $type: "number" } }
{ name: { $regex: /^john/i } }
{ tags: { $size: 3 } } Array Queries
{ tags: "mongodb" } // contains element
{ tags: { $all: ["db", "nosql"] } } // contains all
{ "scores.0": { $gt: 90 } } // first element > 90
{ results: { $elemMatch: { score: { $gte: 90 }, subject: "math" } } } Update Operators
2 snippetsModify documents
Field Updates
{ $set: { name: "New Name" } }
{ $unset: { tempField: "" } }
{ $inc: { views: 1 } }
{ $rename: { "oldName": "newName" } }
{ $mul: { price: 1.1 } } // multiply by 1.1 Array Updates
{ $push: { tags: "new" } }
{ $push: { scores: { $each: [90, 95], $sort: -1, $slice: 5 } } }
{ $pull: { tags: "removed" } }
{ $addToSet: { tags: "unique" } }
{ $pop: { tags: 1 } } // remove last Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Aggregation Pipeline
3 snippetsData processing pipelines
Match & Group
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customerId",
total: { $sum: "$amount" },
count: { $sum: 1 },
avgAmount: { $avg: "$amount" }
}},
{ $sort: { total: -1 } }
]); $lookup (JOIN)
{
$lookup: {
from: "authors",
localField: "authorId",
foreignField: "_id",
as: "author"
}
},
{ $unwind: "$author" } $project
{
$project: {
fullName: { $concat: ["$first", " ", "$last"] },
year: { $year: "$createdAt" },
isActive: { $cond: { if: { $gte: ["$score", 50] }, then: true, else: false } }
}
} Indexes
3 snippetsQuery optimization
Create Indexes
db.users.createIndex({ email: 1 }, { unique: true });
db.posts.createIndex({ title: "text", body: "text" });
db.orders.createIndex({ userId: 1, createdAt: -1 }); TTL & Partial
// Auto-delete after 30 days
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 2592000 });
// Only index active users
db.users.createIndex({ email: 1 }, { partialFilterExpression: { active: true } }); Explain
db.users.find({ email: "a@b.com" }).explain("executionStats");
// Check: executionStats.totalDocsExamined vs nReturned
db.users.getIndexes(); Shell Commands
2 snippetsmongosh essentials
Database Ops
show dbs
use mydb
show collections
db.stats()
db.users.stats()
db.users.countDocuments({ active: true }) Backup & Restore
mongodump --db=mydb --out=/backup/
mongorestore --db=mydb /backup/mydb/
mongodump --uri="mongodb+srv://..." --gzip --archive=backup.gz