MongoDB Basics & CRUD Operations
Learn MongoDB fundamentals from scratch! Understand what MongoDB is, how it organizes data, and master CRUD operations (Create, Read, Update, Delete) with hands-on examples.
Before You Start
Make sure you have MongoDB installed! If you haven't set it up yet, check out the first.
Before we dive into MongoDB, let's understand what a database is. A database is simply a place where we store information in an organized way so we can find it later. Think of it like a digital filing cabinet for your application.
Understanding NoSQL vs SQL
There are two main types of databases:
- SQL Databases (like MySQL, PostgreSQL): Store data in tables with fixed columns and rows, like Excel spreadsheets. You need to define the structure upfront.
- NoSQL Databases (like MongoDB): Store data in flexible formats. MongoDB uses a format similar to JavaScript objects, making it very natural for web developers.
How MongoDB Organizes Data
MongoDB uses three main concepts to organize data:
1. Documents
A document is a single record, like one user's information or one product. It's written in JSON format (the same format as JavaScript objects). Each document can have different fields.
2. Collections
A collection is a group of related documents, like all users or all products. Think of it as a folder containing similar documents.
3. Databases
A database contains multiple collections. For example, an e-commerce app might have a database with collections for users, products, and orders.
Visual Example
// This is what a document looks like// It's just like a JavaScript object!{_id: "507f1f77bcf86cd799439011", // Every document gets a unique IDname: "Alice",email: "alice@example.com",age: 25,hobbies: ["reading", "coding"], // Arrays work perfectlyaddress: { // You can nest objects too!city: "New York",country: "USA"}}// Multiple documents form a collection// Collection name: "users"// Documents: [user1, user2, user3, ...]
Why MongoDB is Perfect for Beginners
- Uses JSON format - if you know JavaScript objects, you already understand MongoDB documents
- No need to plan your entire database structure before starting
- Easy to add new fields to documents without affecting existing data
- Works seamlessly with Node.js and Express
- Free to use and widely adopted in the industry
The MongoDB Shell is an interactive JavaScript interface for MongoDB. It allows you to query and manipulate data directly from your terminal.
Starting the MongoDB Shell:
# Start MongoDB Shell (local installation)mongosh# Or connect to MongoDB Atlas (cloud)mongosh "mongodb+srv://username:password@cluster.mongodb.net/"
Once connected, you'll see a prompt where you can execute MongoDB commands. The shell provides tab completion and command history for easier navigation.
Now that MongoDB is installed, let's learn how to create and work with databases and collections. Don't worry - it's simpler than it sounds!
Important Concept: Lazy Creation
MongoDB doesn't actually create databases or collections until you add data to them. So when you "create" a database, you're really just telling MongoDB "I want to work with this database". It only gets created when you insert your first document.
Step 1: Creating/Switching to a Database
The use command tells MongoDB which database you want to work with. If it doesn't exist, MongoDB will remember the name and create it when you add data.
// Tell MongoDB you want to work with a database called "schoolDB"use schoolDB// MongoDB will create "schoolDB" when you insert your first document// To see all your databasesshow dbs// To see which database you're currently usingdb
Step 2: Understanding Collections
A collection is like a folder that holds similar documents. For example, in a school database, you might have a "students" collection, a "teachers" collection, and a "courses" collection.
The cool thing about MongoDB is that you don't usually need to create collections explicitly. When you insert your first document into a collection, MongoDB creates it automatically!
// This will automatically create a "students" collection if it doesn't existdb.students.insertOne({name: "John",age: 20,major: "Computer Science"})// To see all collections in your current databaseshow collections// If you want to create an empty collection manually (rarely needed)db.createCollection("teachers")
Quick Reference Commands
// Show all databasesshow dbs// Switch to a databaseuse myDatabase// Show current databasedb// Show all collections in current databaseshow collections// Delete a database (be careful!)db.dropDatabase()// Delete a collectiondb.myCollection.drop()
Viewing Data
// View all documents in a collectiondb.students.find()// Pretty-print output for better readabilitydb.students.find().pretty()
Now comes the fun part - adding data to your database! In MongoDB, we call this "inserting" documents. Think of it like adding new entries to your collection.
What Happens When You Insert?
When you insert a document, MongoDB does two important things:
- It saves your document to the collection
- It automatically creates a unique
_idfield if you don't provide one (this is like a serial number for your document)
Method 1: Inserting One Document at a Time
Use insertOne() when you want to add a single document. This is like adding one student's information to your school database.
// Let's add a student to our students collectiondb.students.insertOne({name: "Sarah Johnson",age: 20,major: "Computer Science",email: "sarah@university.edu"})// MongoDB responds with something like:// {// acknowledged: true,// insertedId: ObjectId("507f1f77bcf86cd799439011")// }// The insertedId is the unique ID MongoDB created
Method 2: Inserting Multiple Documents at Once
Use insertMany() when you have multiple documents to add. This is more efficient than calling insertOne() multiple times. Notice how we put the documents in an array [].
// Add multiple students in one godb.students.insertMany([{name: "Mike Chen",age: 21,major: "Mathematics",email: "mike@university.edu"},{name: "Emily Davis",age: 19,major: "Physics",email: "emily@university.edu"},{name: "Raj Patel",age: 22,major: "Engineering",email: "raj@university.edu"}])// MongoDB responds with:// {// acknowledged: true,// insertedIds: {// '0': ObjectId("..."),// '1': ObjectId("..."),// '2': ObjectId("...")// }// }// Each document gets its own unique ID
Understanding the _id Field
Every document in MongoDB must have a unique _id field. If you don't provide one, MongoDB automatically creates an ObjectId for you. You can also provide your own:
// MongoDB creates the _id automaticallydb.students.insertOne({name: "Alex",age: 23})// Result: { _id: ObjectId("..."), name: "Alex", age: 23 }// Or provide your own _iddb.students.insertOne({_id: "STUDENT001",name: "Jordan",age: 24})// Result: { _id: "STUDENT001", name: "Jordan", age: 24 }
Try It Yourself!
Open your MongoDB shell and try inserting a few documents about your favorite books or movies. Practice using both insertOne() and insertMany()!
Now that you've added data, you need to be able to find it again! In MongoDB, we use "find" operations to search for and retrieve documents. Think of it like using a search function or filter in any app.
How Finding Works
When you search for documents, you provide a query (search criteria) in the form of a JavaScript object. MongoDB then returns all documents that match your criteria. If you don't provide any criteria, it returns everything!
Finding All Documents
The simplest query is to find everything in a collection. Just use find() with no parameters:
// Get ALL studentsdb.students.find()// This returns everything! Like selecting all rows in a spreadsheet// To make it easier to read, add .pretty()db.students.find().pretty()// To get just ONE document (any random document)db.students.findOne()
Finding Specific Documents
Usually, you don't want ALL documents - you want specific ones. Pass an object with the fields you want to match:
// Find all students studying Computer Sciencedb.students.find({ major: "Computer Science" })// Find all 20-year-old studentsdb.students.find({ age: 20 })// Find a specific student by namedb.students.findOne({ name: "Sarah Johnson" })// You can match multiple fields - ALL must match!db.students.find({ major: "Computer Science", age: 20 })
Using Comparison Operators
Sometimes you need more than exact matches. MongoDB has special operators that start with $ for comparing values:
// Find students OLDER than 20db.students.find({ age: { $gt: 20 } }) // $gt = greater than// Find students 20 or olderdb.students.find({ age: { $gte: 20 } }) // $gte = greater than or equal// Find students younger than 25db.students.find({ age: { $lt: 25 } }) // $lt = less than// Find students between 20 and 22 (inclusive)db.students.find({age: { $gte: 20, $lte: 22 } // $lte = less than or equal})// Find students NOT studying Engineeringdb.students.find({ major: { $ne: "Engineering" } }) // $ne = not equal// Find students in specific majorsdb.students.find({major: { $in: ["Computer Science", "Mathematics", "Physics"] }}) // $in = any of these values
Quick Reference: Comparison Operators
$gt — Greater than (>)
$gte — Greater than or equal (≥)
$lt — Less than (<)
$lte — Less than or equal (≤)
$eq — Equal to (=)
$ne — Not equal (≠)
$in — Matches any value in an array
Combining Conditions with Logical Operators
Sometimes you need more complex searches. MongoDB has logical operators like AND and OR:
// Find students who are Computer Science majors AND over 20db.students.find({$and: [{ major: "Computer Science" },{ age: { $gt: 20 } }]})// Actually, you can write AND conditions more simply:db.students.find({major: "Computer Science",age: { $gt: 20 }}) // Multiple fields = automatic AND!// Find students who are EITHER in Physics OR Mathematicsdb.students.find({$or: [{ major: "Physics" },{ major: "Mathematics" }]}) // At least one condition must be true
Selecting Specific Fields (Projection)
Sometimes you don't need all the information from a document - just specific fields. This is called projection. It's like choosing which columns to display in a spreadsheet.
// Get ONLY the names and emails (hide everything else)db.students.find({}, // First parameter: search criteria (empty = all){ name: 1, email: 1, _id: 0 } // Second parameter: which fields to show)// 1 = include this field// 0 = exclude this field// Result: Only name and email are returned// Get everything EXCEPT the agedb.students.find({}, { age: 0 })// Find Computer Science students, show only their namesdb.students.find({ major: "Computer Science" },{ name: 1, _id: 0 })
Sorting Results
You can sort your results in ascending or descending order using sort():
// Sort by age (ascending: youngest first)db.students.find().sort({ age: 1 }) // 1 = ascending// Sort by age (descending: oldest first)db.students.find().sort({ age: -1 }) // -1 = descending// Sort by multiple fields: first by major, then by agedb.students.find().sort({ major: 1, age: -1 })
Limiting and Skipping Results
For large collections, you might want to limit how many results you get or skip some results (useful for pagination):
// Get only the first 5 studentsdb.students.find().limit(5)// Skip the first 10 students, then get the next 5db.students.find().skip(10).limit(5)// This is how pagination works!// Count how many documents matchdb.students.find({ major: "Computer Science" }).count()// Chain them all together: find, sort, skip, limitdb.students.find({ age: { $gte: 20 } }).sort({ age: 1 }).skip(0).limit(10)
After inserting data, you'll often need to change it. Maybe a student changes their major, or their age increases, or you need to add new information. In MongoDB, we "update" documents to modify existing data.
Important Concept: Update Operators
When updating, you don't directly set values. Instead, you use update operators that start with $ to tell MongoDB HOW to update the data. The most common is $set, which sets a field to a new value.
Think of it like giving instructions: "SET the major to Computer Science" or "INCREASE the age by 1".
Updating One Document
Use updateOne() to modify the first document that matches your search criteria. It has two parts: what to find and what to change.
// Update Sarah's major to Data Sciencedb.students.updateOne({ name: "Sarah Johnson" }, // WHAT TO FIND: Find Sarah{ $set: { major: "Data Science" } } // WHAT TO CHANGE: Set new major)// Update multiple fields at oncedb.students.updateOne({ name: "Mike Chen" },{$set: {major: "Computer Science",email: "mike.new@university.edu"}})// If the field doesn't exist, it will be added!db.students.updateOne({ name: "Emily Davis" },{ $set: { gpa: 3.8 } } // Adds a new "gpa" field)
Updating Multiple Documents
Use updateMany() when you want to update ALL documents that match your criteria. Perfect for bulk updates!
// Give all Computer Science students a new fielddb.students.updateMany({ major: "Computer Science" },{ $set: { department: "CS Department" } })// Add a status field to all students under 21db.students.updateMany({ age: { $lt: 21 } },{ $set: { status: "underclassman" } })
More Update Operators
Besides $set, there are other useful operators for different types of updates:
// $inc - Increase (or decrease) a number// Useful for ages, scores, counters, etc.db.students.updateOne({ name: "Sarah Johnson" },{ $inc: { age: 1 } } // Increase age by 1)// Decrease by using negative numbersdb.students.updateOne({ name: "Mike Chen" },{ $inc: { age: -1 } } // Decrease age by 1)// $unset - Remove a field completelydb.students.updateOne({ name: "Emily Davis" },{ $unset: { gpa: "" } } // Remove the gpa field)// $rename - Change the name of a fielddb.students.updateMany({}, // All documents{ $rename: { "email": "emailAddress" } } // Rename field)
Working with Arrays
If a field contains an array (like a list of hobbies or courses), you can add or remove items:
// First, let's add a hobbies array to a studentdb.students.updateOne({ name: "Sarah Johnson" },{ $set: { hobbies: ["reading", "coding"] } })// $push - Add an item to an arraydb.students.updateOne({ name: "Sarah Johnson" },{ $push: { hobbies: "gaming" } } // Now: ["reading", "coding", "gaming"])// $pull - Remove a specific item from an arraydb.students.updateOne({ name: "Sarah Johnson" },{ $pull: { hobbies: "gaming" } } // Back to: ["reading", "coding"])// Add multiple items at oncedb.students.updateOne({ name: "Sarah Johnson" },{ $push: { hobbies: { $each: ["music", "sports"] } } })
Quick Reference: Update Operators
$set — Set a field to a new value (or create it if it doesn't exist)
$inc — Increase or decrease a number
$unset — Remove a field
$rename — Rename a field
$push — Add an item to an array
$pull — Remove an item from an array
Sometimes you need to remove data from your database. Maybe a student graduates, or you need to clean up old records. In MongoDB, we "delete" documents to remove them permanently.
Warning: Deletions are Permanent!
Unlike updating where you can change data back, deleted documents are gone forever. Always be careful with delete operations, especially deleteMany()! It's a good idea to run a find() query first to see what you're about to delete.
Deleting One Document
Use deleteOne() to remove a single document. If multiple documents match, only the first one found will be deleted.
// Delete a specific student by namedb.students.deleteOne({ name: "Mike Chen" })// Delete the first student who is under 18db.students.deleteOne({ age: { $lt: 18 } })// Tip: First check what you're deleting!db.students.find({ name: "Mike Chen" }) // Check if this is what you wantdb.students.deleteOne({ name: "Mike Chen" }) // Then delete
Deleting Multiple Documents
Use deleteMany() to remove ALL documents that match your criteria. Be extra careful with this one!
// DANGER! This deletes ALL Computer Science studentsdb.students.deleteMany({ major: "Computer Science" })// Delete all students under 18db.students.deleteMany({ age: { $lt: 18 } })// Pro tip: Check what you're deleting first!db.students.find({ major: "Computer Science" }).count() // How many?db.students.deleteMany({ major: "Computer Science" }) // Then delete// MongoDB tells you how many were deleted:// { acknowledged: true, deletedCount: 5 }
Deleting Everything from a Collection
To delete ALL documents but keep the collection:
// Delete every single document (VERY DANGEROUS!)db.students.deleteMany({}) // Empty object = match everything// Or just drop the entire collection:db.students.drop() // Removes collection completely// Returns: true
Deleting an Entire Database
To remove an entire database with all its collections:
// Make absolutely sure you're in the right database!db // Check which database you're in// Then drop itdb.dropDatabase()// Confirm it's goneshow dbs // Database won't appear anymore
Pro Tip: Always Test First!
Run a find() query with the same criteria before deleting. This lets you see exactly what will be deleted. Think of it like looking in the trash can before emptying it!
Congratulations!
You've learned the fundamentals of MongoDB and CRUD operations! You can now create databases, add data, search for it, update it, and delete it.
Next, learn how to use MongoDB in your Node.js applications with the MongoDB driver and Mongoose!