Cheatsheet - Cheatsheet
Shell & Database Commands
Command | Description |
---|---|
mongosh |
Starts the MongoDB Shell and connects to a local instance. |
mongosh "mongodb://host:port" |
Connects the shell to a specific host and port. |
show dbs |
Lists all databases on the server. |
use <db_name> |
Switches to a database. If it doesn't exist, it's created upon first data insertion. |
db |
Shows the current database. |
db.stats() |
Displays stats for the current database. |
db.dropDatabase() |
Deletes the entire current database. |
exit or Ctrl+D |
Exits the MongoDB shell. |
Collection Commands
Collections are analogous to tables in SQL databases.
Command | Description |
---|---|
show collections |
Lists all collections in the current database. |
db.createCollection("coll_name") |
Explicitly creates a new collection. |
db.coll_name.stats() |
Displays stats for the specified collection. |
db.coll_name.drop() |
Deletes the entire collection. |
db.coll_name.renameCollection("new_name") |
Renames a collection. |
CRUD Operations: Create (Insert)
-
Insert a Single Document:
db.inventory.insertOne({ item: 'canvas', qty: 100, tags: ['cotton'], size: { h: 28, w: 35.5, uom: 'cm' }, });
-
Insert Multiple Documents:
db.inventory.insertMany([ { item: 'journal', qty: 25, tags: ['blank', 'red'], size: { h: 14, w: 21, uom: 'cm' }, }, { item: 'mat', qty: 85, tags: ['gray'], size: { h: 27.9, w: 35.5, uom: 'cm' }, }, ]);
CRUD Operations: Read (Query)
The find()
method is used for all queries.
-
Find All Documents:
db.inventory.find({});
-
Find a Single Document:
db.inventory.findOne({ item: 'journal' });
-
Pretty Print Results:
db.inventory.find({}).pretty();
Query Filters (The first argument to find()
)
-
Equality:
// Find documents where qty is 25 db.inventory.find({ qty: 25 }); // Find documents with a nested field match db.inventory.find({ 'size.h': 14 });
-
Comparison Operators:
Operator Meaning Example $eq
Equals { qty: { $eq: 25 } }
(same as{ qty: 25 }
)$gt
Greater Than { qty: { $gt: 20 } }
$gte
Greater Than or Equal { qty: { $gte: 25 } }
$lt
Less Than { qty: { $lt: 30 } }
$lte
Less Than or Equal { qty: { $lte: 25 } }
$ne
Not Equal { item: { $ne: "canvas" } }
$in
In an Array of values { qty: { $in: [25, 85] } }
$nin
Not in an Array of values { item: { $nin: ["journal", "mat"] } }
-
Logical Operators:
// AND (implicit when using comma-separated fields) db.inventory.find({ item: 'mat', qty: { $gt: 50 } }); // OR db.inventory.find({ $or: [{ item: 'journal' }, { qty: { $lt: 50 } }] });
-
Array Operators:
// Find where the tags array contains "red" db.inventory.find({ tags: 'red' }); // Find where the tags array contains both "gray" and "canvas" db.inventory.find({ tags: { $all: ['gray', 'canvas'] } });
Cursors (Modifying Query Results)
Chain these methods after a find()
call.
-
Projections (Selecting specific fields):
// Return only the item and qty fields (and _id by default) db.inventory.find({}, { item: 1, qty: 1 }); // Exclude the _id field db.inventory.find({}, { item: 1, qty: 1, _id: 0 });
-
Sorting:
1
for ascending,-1
for descending.db.inventory.find({}).sort({ qty: -1 });
-
Limiting & Skipping (for pagination):
// Get the first 5 documents db.inventory.find({}).limit(5); // Skip the first 5 documents and get the next 5 db.inventory.find({}).skip(5).limit(5);
-
Counting:
db.inventory.countDocuments({ item: 'journal' });
CRUD Operations: Update
-
Update a Single Document:
db.inventory.updateOne( { item: 'journal' }, // Filter { $set: { 'size.uom': 'in' }, $currentDate: { lastModified: true } } // Update operator );
-
Update Multiple Documents:
db.inventory.updateMany( { qty: { $lt: 50 } }, // Filter { $set: { status: 'low_stock' } } // Update operator );
-
Replace a Single Document:
db.inventory.replaceOne( { item: 'canvas' }, // Filter { item: 'canvas_new', qty: 120, tags: ['paint'] } // Replacement document );
Common Update Operators
Operator | Description |
---|---|
$set |
Sets the value of a field. Creates the field if it doesn't exist. |
$unset |
Removes the specified field from a document. |
$inc |
Increments the value of a field by a specified amount. |
$rename |
Renames a field. |
$currentDate |
Sets the value of a field to the current date. |
$push |
Appends a value to an array. |
$pull |
Removes all array elements that match a specified query. |
$addToSet |
Adds elements to an array only if they do not already exist. |
CRUD Operations: Delete
-
Delete a Single Document:
db.inventory.deleteOne({ item: 'canvas_new' });
-
Delete Multiple Documents:
db.inventory.deleteMany({ status: 'low_stock' });
Warning:
db.inventory.deleteMany({})
will delete all documents in the collection.
Indexes
Indexes improve query performance.
Command | Description |
---|---|
db.collection.createIndex({ field: 1 }) |
Creates an ascending index on field . Use -1 for descending. |
db.collection.createIndex({ field1: 1, field2: -1 }) |
Creates a compound index. |
db.collection.createIndex({ field: 1 }, { unique: true }) |
Creates a unique index. |
db.collection.getIndexes() |
Lists all indexes on a collection. |
db.collection.dropIndex("index_name") |
Drops a specific index. |
Aggregation Framework
Performs multi-stage data processing.
-
Basic Pipeline Structure:
db.collection.aggregate([ { $stage1: { ... } }, { $stage2: { ... } }, // ... ])
-
Example: Group by a field and calculate an average.
db.orders.aggregate([ // Stage 1: Filter for orders with status "A" { $match: { status: 'A' } }, // Stage 2: Group by customer ID and sum the amounts { $group: { _id: '$cust_id', total: { $sum: '$amount' } } }, // Stage 3: Sort by the new total field { $sort: { total: -1 } }, ]);