CRUD Command Cheat Sheet
The four CRUD operations map directly to shell and driver methods: insertOne()/insertMany() create documents, find()/findOne() read them with an optional filter and projection, updateOne()/updateMany() modify fields using update operators like $set and $inc, and deleteOne()/deleteMany() remove documents matching a filter. Every write method accepts a filter as its first argument and, for updates, an update document as its second, with an optional options object third for things like upsert or arrayFilters.
Cricket analogy: Like a scorer's four basic actions — record a new ball, look up an over, amend a run total, and strike out a no-ball — MongoDB's CRUD methods map directly to create, read, update, and delete operations.
// Create
db.users.insertOne({ name: "Ada", age: 28, roles: ["admin"] });
db.users.insertMany([{ name: "Grace" }, { name: "Alan" }]);
// Read
db.users.find({ age: { $gte: 18 } }, { name: 1, _id: 0 });
db.users.findOne({ name: "Ada" });
// Update
db.users.updateOne({ name: "Ada" }, { $set: { age: 29 } });
db.users.updateMany({ roles: "admin" }, { $inc: { loginCount: 1 } });
// Delete
db.users.deleteOne({ name: "Alan" });
db.users.deleteMany({ age: { $lt: 13 } });Common Query Operators
Common query operators fall into a few families: comparison ($eq, $ne, $gt, $gte, $lt, $lte, $in, $nin), logical ($and, $or, $not, $nor), element ($exists, $type), and array ($all, $elemMatch, $size). Because these operators are keys in a query document and start with a dollar sign, they must be written as quoted strings in the shell (e.g. { age: { '$gte': 18 } }) and are evaluated against each document's field values to build the filter used by find, update, and delete operations.
Cricket analogy: Like a stats filter distinguishing 'greater than 50 runs' from 'exactly 50 runs' from 'not out,' MongoDB's $gt, $eq, and $ne operators express these same precise comparisons in a query filter.
In the mongosh shell, dollar-prefixed operators must be quoted string keys, e.g. db.users.find({ age: { $gte: 18 } }) — this is valid because JavaScript object keys with special characters like $ are written unquoted here, but always wrap them correctly when building queries dynamically from variables to avoid injection issues.
Index and Aggregation Quick Reference
For performance, createIndex({ field: 1 }) builds an ascending single-field index, while compound indexes like createIndex({ status: 1, createdAt: -1 }) speed up queries that filter and sort on multiple fields together, following the ESR (Equality, Sort, Range) ordering rule. The aggregation framework chains stages like $match (filter), $group (aggregate), $sort, $project (reshape), and $lookup (join) into a pipeline, and placing $match as early as possible reduces the number of documents later stages have to process.
Cricket analogy: Like a stats database indexed first by 'team' then by 'match date' to answer 'this team's most recent matches' quickly, a compound index on status then createdAt speeds up exactly this kind of filtered, sorted query.
Avoid the deprecated $where operator and unindexed regex queries with a leading wildcard (e.g. /.*smith/) for filtering, since both force a full collection scan (COLLSCAN) and execute JavaScript per document or scan every value, which is significantly slower than an indexed comparison operator at scale.
- CRUD maps to insertOne/insertMany, find/findOne, updateOne/updateMany, and deleteOne/deleteMany.
- Query operators fall into comparison, logical, element, and array families, all written as quoted $-prefixed keys.
- createIndex({ field: 1 }) builds an ascending index; compound indexes should follow the ESR rule.
- The aggregation pipeline chains stages like $match, $group, $sort, $project, and $lookup.
- Placing $match early in a pipeline reduces the documents later stages must process.
- Avoid $where and leading-wildcard regex filters since they force full collection scans.
- Use explain('executionStats') to verify a query is using an index rather than scanning the whole collection.
Practice what you learned
1. Which method updates a single document's fields without replacing the whole document?
2. How must dollar-prefixed query operators be written in a query document?
3. What is the recommended field order for a compound index under the ESR rule?
4. Why should $match be placed early in an aggregation pipeline?
5. Why should the $where operator generally be avoided?
Was this page helpful?
You May Also Like
MongoDB Interview Questions
A curated set of commonly asked MongoDB interview questions and concepts, covering data modeling, indexing, replication, and sharding fundamentals.
Replica Sets Explained
How MongoDB replica sets provide high availability through automatic failover, elections, and data redundancy across primary and secondary nodes.
Sharding in MongoDB
How MongoDB distributes data across multiple shards using shard keys, chunks, and a query router to scale horizontally beyond a single server's capacity.