Namaste, future FullStackDost! In the world of databases, managing data effectively is paramount. Whether you’re building a social media app, an e-commerce platform, or a data analytics tool, you’ll constantly be performing four fundamental operations: Create, Read, Update, and Delete – collectively known as CRUD. These are the heartbeats of any data-driven application.
In this lesson, we’ll dive deep into how MongoDB, our powerful NoSQL database, handles these CRUD operations. We’ll use the mongosh interactive shell to execute commands directly, giving you hands-on experience. So, let’s get started and make our data dance!
Graphics Suggestion: An EduPress-style clean infographic showing four distinct icons for Create (e.g., a plus sign or document with a star), Read (e.g., a magnifying glass), Update (e.g., a pencil or refresh arrows), and Delete (e.g., a trash can). Each icon could be linked to a MongoDB logo.
Creating data means adding new documents to a MongoDB collection. Think of a collection as a table in a relational database, but instead of rows, we have flexible JSON-like documents.
Before we begin, ensure your MongoDB server is running and you’re connected via mongosh. We’ll be working with a database named fstackdost_db and a collection named users. If they don’t exist, MongoDB will create them automatically when you first insert data!
// Switch to (or create) our database
use fstackdost_db;
// Output: switched to db fstackdost_db
insertOne(): Adding a Single DocumentThe insertOne() method is used to add a single document into a specified collection. It’s straightforward and perfect for individual entries.
// Example: Adding a new user, John Doe
db.users.insertOne({
name: "John Doe",
age: 30,
email: "john.doe@example.com",
interests: ["coding", "reading"],
address: {
street: "123 Main St",
city: "Techville"
}
});
/*
Expected Output:
{
acknowledged: true,
insertedId: ObjectId("...") // A unique ID generated by MongoDB
}
*/
Notice how MongoDB automatically assigns a unique _id to each document if you don’t provide one. This _id acts as the primary key.
insertMany(): Adding Multiple DocumentsWhen you need to add several documents at once, insertMany() is your go-to method. It takes an array of document objects as its argument, making bulk inserts efficient.
// Example: Adding multiple users in one go
db.users.insertMany([
{
name: "Jane Smith",
age: 25,
email: "jane.smith@example.com",
interests: ["hiking", "photography"]
},
{
name: "Alice Johnson",
age: 28,
email: "alice.j@example.com",
interests: ["gaming", "cooking"],
status: "active"
},
{
name: "Bob Williams",
age: 35,
email: "bob.w@example.com",
interests: ["coding", "sports"]
}
]);
/*
Expected Output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId("..."),
'1': ObjectId("..."),
'2': ObjectId("...")
}
}
*/
Graphics Suggestion: Two document icons, one with a single plus sign (for insertOne) and another with multiple plus signs (for insertMany), both pointing towards a database icon.
Reading data means querying and fetching documents from your collections. MongoDB offers powerful and flexible ways to find exactly what you need.
find(): Querying Multiple DocumentsThe find() method is the primary way to query documents. When called without any arguments, it returns all documents in a collection. However, its real power comes from its ability to filter, sort, and project data.
// Example: Find all documents in the 'users' collection
db.users.find();
/*
Expected Output (formatted for readability):
[
{
_id: ObjectId("..."),
name: 'John Doe',
age: 30,
email: 'john.doe@example.com',
interests: [ 'coding', 'reading' ],
address: { street: '123 Main St', city: 'Techville' }
},
{
_id: ObjectId("..."),
name: 'Jane Smith',
age: 25,
email: 'jane.smith@example.com',
interests: [ 'hiking', 'photography' ]
},
// ... more documents
]
*/
To make the output more readable in mongosh, you can chain .pretty():
db.users.find().pretty();
To find specific documents, you pass a query document (a JavaScript object) to find(). This object specifies the conditions that documents must meet.
// Example: Find users who are 30 years old
db.users.find({ age: 30 });
// Example: Find users whose name is "Jane Smith" AND age is 25
db.users.find({ name: "Jane Smith", age: 25 });
// Example: Find users older than 28 using the $gt (greater than) operator
db.users.find({ age: { $gt: 28 } });
// Example: Find users whose interests include "coding"
db.users.find({ interests: "coding" });
MongoDB supports a rich set of query operators like $lt (less than), $gte (greater than or equal), $in (value in an array), $or, and more.
Sometimes you don’t need all the fields from a document. Projection allows you to specify which fields to include or exclude in the result. You pass a second document to find(), where 1 includes the field and 0 excludes it.
// Example: Find all users, but only return their name and email
db.users.find({}, { name: 1, email: 1, _id: 0 }); // _id is included by default, so we explicitly exclude it
/*
Expected Output:
[
{ name: 'John Doe', email: 'john.doe@example.com' },
{ name: 'Jane Smith', email: 'jane.smith@example.com' },
// ...
]
*/
You can chain additional methods to find() to further refine your results:
.sort({ field: 1/-1 }): Sorts the results. 1 for ascending, -1 for descending..limit(N): Restricts the number of documents returned to N.
// Example: Find users older than 25, sort by age ascending, and limit to 2 results
db.users.find({ age: { $gt: 25 } }).sort({ age: 1 }).limit(2);
findOne(): Retrieving a Single DocumentIf you expect only one document to match your query (e.g., finding a user by a unique email), findOne() is more efficient. It returns the first document that matches the query, or null if no document is found.
// Example: Find a user by their unique email
db.users.findOne({ email: "john.doe@example.com" });
countDocuments(): Counting MatchesTo simply get the number of documents that match a certain query, use countDocuments(). This is more efficient than fetching all documents and then counting them.
// Example: Count users older than 25
db.users.countDocuments({ age: { $gt: 25 } });
// Expected Output: 3 (or whatever matches your data)
// Example: Count all documents in the collection
db.users.countDocuments({});
Graphics Suggestion: A magnifying glass icon hovering over a stack of documents, with a filter funnel icon next to it, and a small counter (e.g., “3 results”) appearing at the bottom. This represents filtering, finding, and counting.
Update operations allow you to change the data within existing documents. MongoDB provides methods to update a single document, multiple documents, or even replace an entire document.
updateOne(): Updating the First MatchThis method updates a single document that matches the specified filter. It takes two main arguments: the query filter and an update document (which typically uses update operators).
// Example: Update John Doe's age to 31 and add a new interest
db.users.updateOne(
{ name: "John Doe" }, // Query filter: find John Doe
{
$set: { age: 31, status: "active" }, // Set new age and status
$push: { interests: "photography" } // Add 'photography' to interests array
}
);
/*
Expected Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1, // Number of documents that matched the query
modifiedCount: 1 // Number of documents that were actually changed
}
*/
updateMany(): Updating All MatchesIf your query matches multiple documents and you want to apply changes to all of them, updateMany() is the method to use.
// Example: Increment the age of all users older than 25 by 1
db.users.updateMany(
{ age: { $gt: 25 } }, // Query filter: find users older than 25
{ $inc: { age: 1 } } // Update operation: increment age by 1
);
/*
Expected Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 3, // Assuming 3 users matched
modifiedCount: 3
}
*/
replaceOne(): Replacing an Entire DocumentBe careful with replaceOne()! It replaces the *entire* document that matches the query with a new document. The _id field remains, but all other fields are overwritten unless explicitly included in the replacement document.
// Example: Replace John Doe's document completely
db.users.replaceOne(
{ email: "john.doe@example.com" }, // Query filter
{
name: "Jonathan Doe", // New name
age: 32,
email: "jonathan.doe@example.com", // Updated email
occupation: "Software Engineer" // New field, old fields like 'interests' and 'address' are removed
}
);
/*
Expected Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1
}
*/
After this, John Doe’s document will only have _id, name, age, email, and occupation. His old `interests` and `address` fields are gone!
MongoDB provides a rich set of update operators to perform specific modifications:
$set: Sets the value of a field. If the field does not exist, $set adds the new field with the specified value.$inc: Increments the value of a field by a specified amount. Works only with numeric values.$push: Adds a value to an array field. If the field is not an array, it creates it.$pull: Removes all instances of a specified value from an array.$unset: Removes a specified field from a document.$rename: Renames a field.Graphics Suggestion: A document icon with a “gear” or “wrench” icon overlaid, representing modification. Smaller icons for $set (equals sign), $inc (plus sign), $push (arrow into a box), $pull (arrow out of a box), $unset (X mark) could appear around it.
Deleting operations allow you to remove documents or even entire collections from your database. Use these operations with caution, as deleted data is often irrecoverable without backups!
deleteOne(): Deleting the First MatchThis method deletes at most one document that matches the specified query filter. It’s useful for removing unique entries.
// Example: Delete the user whose email is 'jane.smith@example.com'
db.users.deleteOne({ email: "jane.smith@example.com" });
/*
Expected Output:
{ acknowledged: true, deletedCount: 1 }
*/
deleteMany(): Deleting All MatchesTo remove multiple documents that satisfy a given filter, use deleteMany(). If you pass an empty query document {}, it will delete *all* documents in the collection.
// Example: Delete all users whose age is less than or equal to 25
db.users.deleteMany({ age: { $lte: 25 } });
/*
Expected Output:
{ acknowledged: true, deletedCount: 1 } // Or more, depending on your data
*/
// CAUTION: This will delete ALL documents in the 'users' collection!
// db.users.deleteMany({});
drop(): Removing an Entire CollectionThe drop() method is the most drastic deletion operation. It completely removes a collection from the database, including all its documents and indexes. This is irreversible!
// Example: Drop the entire 'users' collection
db.users.drop();
/*
Expected Output:
true // Indicates successful deletion
*/
Graphics Suggestion: A large trash can icon. For deleteOne, a single document falling in. For deleteMany, multiple documents falling in. For drop(), the entire stack of documents (representing a collection) falling into the trash.
Now it’s your turn! Open your mongosh terminal and perform the following operations. You can create a new database called fstackdost_practice for this.
products. The document should have fields like name, price, category, and stock.products collection using a single command. Ensure one product has a category of “Electronics” and another has “Books”.products collection.price greater than 50.name and price. Exclude the _id.stock less than 10.price of one specific product (e.g., by its name) to a new value.stock by 5.last_updated with the current date (new Date()) to all products with a stock greater than 20.name.stock of 0.price in descending order, and limit the results to the top 2 most expensive products.Fantastic work! You’ve just mastered the four pillars of data management in MongoDB: Create, Read, Update, and Delete. These CRUD operations are not just commands; they are the fundamental interactions you’ll have with your database, forming the backbone of almost every application you’ll ever build.
Remember, practice is key! The more you experiment with these commands in mongosh, the more intuitive they will become. You now have the essential tools to manage data effectively in MongoDB, setting a strong foundation for your full-stack development journey. Keep building, keep learning!