MongoDB Cheatsheet
21 essential methods for coding interviews
Showing 21 of 21 methods
| Method | Syntax | Description | Time | Priority |
|---|---|---|---|---|
find | db.collection.find(query, projection) | Find documents matching query criteria | O(n) | essential |
insertOne | db.collection.insertOne(document) | Insert a single document into collection | O(1) | essential |
updateOne | db.collection.updateOne(filter, update, options) | Update first document matching filter | O(1) | essential |
deleteOne | db.collection.deleteOne(filter) | Delete first document matching filter | O(1) | essential |
$gt, $gte | {field: {$gt: value}} or {field: {$gte: value}} | Greater than (>) or greater than or equal (>=) | O(n) | essential |
$in, $nin | {field: {$in: [value1, value2]}} or {field: {$nin: [...]}} | Match any value in array (in) or not in array (nin) | O(n) | essential |
$and, $or | {$and: [condition1, condition2]} or {$or: [condition1, condition2]} | Logical AND and OR operators | O(n) | essential |
$set | {$set: {field: value}} | Set field value (creates field if missing) | O(1) | essential |
$inc | {$inc: {field: number}} | Increment numeric field by specified amount | O(1) | essential |
$push | {$push: {arrayField: value}} | Add element to end of array | O(1) | essential |
$pull | {$pull: {arrayField: value}} | Remove all occurrences of value from array | O(n) | essential |
$match | {$match: {query}} | Filter documents (like WHERE in SQL) | O(n) | essential |
$group | {$group: {_id: "$field", alias: {$operator: "$field"}}} | Group documents and apply aggregation operators | O(n) | essential |
$project | {$project: {field1: 1, field2: 0, newField: "$oldField"}} | Reshape documents, include/exclude fields, add computed fields | O(n) | essential |
$sort | {$sort: {field1: 1, field2: -1}} | Sort documents (1 = ascending, -1 = descending) | O(n log n) | essential |
$regex | {field: {$regex: /pattern/, $options: "i"}} | Pattern matching with regular expressions | O(n) | common |
$lookup | {$lookup: {from: "collection", localField: "field", foreignField: "field", as: "alias"}} | Left outer join with another collection | O(n * m) | common |
$elemMatch | {arrayField: {$elemMatch: {condition}}} | Match documents where array contains element matching condition | O(n) | common |
createIndex | db.collection.createIndex({field: 1}, {options}) | Create index on field(s) for faster queries | O(n log n) | common |
$size | {arrayField: {$size: number}} | Match arrays of exact size | O(n) | useful |
text index | db.collection.createIndex({field: "text"}) | Create text index for full-text search | O(n log n) | useful |