
MongoDB Shell Crash Course
Table of Contents
Open Table of Contents
Introduction
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. This structure allows for dynamic schemas, making it a preferred choice for modern applications that require scalability and performance.
Prerequisites
- Node.js: Ensure you have Node.js installed on your system. You can download it from the official website.
-
Start the MongoDB Server: Run the following command to start the MongoDB server:
mongodBy default, MongoDB listens on port 27017.
-
Access the MongoDB Shell: Open a new terminal window and execute:
mongoshThis command opens the MongoDB shell, allowing you to interact with your databases.
Understanding MongoDB
Databases and Collections
- Database: A container for collections. Each database gets its own set of files on the file system.
- Collection: A group of MongoDB documents, akin to a table in relational databases.
Documents
Documents are the basic units of data in MongoDB, stored in a format called BSON (Binary JSON). An example document:
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "John Doe",
"age": 29,
"email": "johndoe@example.com",
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
}
}
To list the databases on the mongodb instance:
show dbs;
By default, the ‘test’ database is selected. To switch to a different database or create a new one, type the use-command with the database name:
use mydb;
To list all collections within the selected databse:
show collections;
Basic CRUD Operations
1. Create (Insert)
To add a new document to a collection:
db.users.insertOne({
"name": "Jane Smith",
"age": 32,
"email": "janesmith@example.com"
});
2. Read (Find)
Retrieve documents from a collection:
// Find all documents
db.users.find();
// Find documents with a specific condition
db.users.find({ "age": 30 });
3. Update
Modify existing documents:
// Update a single document
db.users.updateOne(
{ "name": "Jane Smith" },
{ $set: { "age": 33 } }
);
// Update multiple documents
db.users.updateMany(
{ "age": { $lt: 25 } },
{ $set: { "status": "Underage" } }
);
4. Delete
Remove documents from a collection:
// Delete a single document
db.users.deleteOne({ "name": "Jane Smith" });
// Delete multiple documents
db.users.deleteMany({ "status": "Underage" });
Indexes
Indexes support the efficient execution of queries. Without indexes, MongoDB must perform a collection scan, i.e., scan every document in a collection, to select those documents that match the query statement.
Creating an Index
// Create an index on the 'email' field
db.users.createIndex({ "email": 1 });
Viewing Indexes
// List all indexes on the 'users' collection
db.users.getIndexes();
Testing query against Index
You can check whether given query benefits from the Indexes you have, with the explain() method. It will return the execution plan of the query.
// Explain the execution plan of the following 'find(...)' query
db.users.find({"email" : "janesmith@example.com"}).explain();
Look inside the “queryPlanner” -> “winningPlan”. Look for “stage” values:
- stage = IXSCAN -----> index is being used
- stage = COLLSCAN -----> index is NOT being used
Aggregation
Aggregation operations process data records and return computed results. They are useful for operations such as grouping values from multiple documents or performing operations on grouped data.
Example: Aggregation Pipeline
db.orders.aggregate([
{ $match: { "status": "shipped" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
]);
In order to run the above Aggregation Pipeline, you need to insert the the array of documents into the ‘orders’ collection:
[{"customerId":"CUST-001","customerName":"Jane Smith","status":"processing","amount":150.0,"time":"2026-01-12T10:15:30Z"},{"customerId":"CUST-002","customerName":"Michael Johnson","status":"shipped","amount":90.5,"time":"2026-01-13T14:22:10Z"},{"customerId":"CUST-001","customerName":"Jane Smith","status":"shipped","amount":50.0,"time":"2026-01-14T09:05:45Z"},{"customerId":"CUST-003","customerName":"Emily Davis","status":"processing","amount":230.0,"time":"2026-01-15T16:40:00Z"},{"customerId":"CUST-001","customerName":"Jane Smith","status":"shipped","amount":200.0,"time":"2026-01-16T11:55:20Z"},{"customerId":"CUST-001","customerName":"Jane Smith","status":"shipped","amount":200.0,"time":"2026-02-16T11:56:30Z"},{"customerId":"CUST-004","customerName":"Robert Brown","status":"cancelled","amount":0,"time":"2026-01-17T08:30:00Z"},{"customerId":"CUST-002","customerName":"Michael Johnson","status":"shipped","amount":100.0,"time":"2026-02-13T15:23:10Z"}]