Introduction to CRUD Operations in MongoDB
Hello, fellow code enthusiasts! Welcome to another exciting tutorial on sagarkunwar.com.np — your go-to place for building apps, websites, and projects from scratch. Today, we’re diving into the world of databases, specifically focusing on CRUD operations in MongoDB!
Whether you’re building your first app or just curious about MongoDB, understanding how to perform basic CRUD operations is essential. Let’s break it all down into simple steps.
What is MongoDB?
Before we dive into CRUD operations, let’s talk a bit about MongoDB itself. MongoDB is a NoSQL database, meaning it’s designed to store large volumes of data without the need for a predefined schema. This makes it extremely flexible and scalable, perfect for modern applications.
In MongoDB, data is stored in JSON-like documents, which means more naturally mapped to how we work with data in real life. Cool, right?
CRUD Operations: The Basics
CRUD stands for Create, Read, Update, and Delete. These are the fundamental operations you’ll perform on a database. Let’s explore each one with examples.
1. Create
The “C” in CRUD stands for Create. In the context of a database, this means adding new records. In MongoDB, you accomplish this with the insertOne() or insertMany() methods.
Example:
javascript
// Assuming you have a MongoDB client connected
const newDocument = { name: "Alice", age: 28, city: "Kathmandu" };
// Use insertOne for a single document
db.collection('users').insertOne(newDocument, (err, res) => {
if (err) throw err;
console.log("Document inserted");
});
// To insert multiple documents:
// const newDocuments = [{...}, {...}];
// db.collection('users').insertMany(newDocuments, callbackFunction);
2. Read
Reading is all about fetching data from your database. MongoDB provides a variety of methods like find() and findOne() to query documents.
Example:
javascript
// Find all users named 'Alice'
db.collection('users').find({ name: "Alice" }).toArray((err, results) => {
if (err) throw err;
console.log(results);
});
// Finding a single document
db.collection('users').findOne({ name: "Alice" }, (err, result) => {
if (err) throw err;
console.log(result);
});
3. Update
Updating involves modifying existing documents. You can update specific fields or entire documents using methods like updateOne(), updateMany(), or replaceOne().
Example:
javascript
// Update age of the user named 'Alice'
db.collection('users').updateOne(
{ name: "Alice" },
{ $set: { age: 29 } },
(err, res) => {
if (err) throw err;
console.log("Document updated");
}
);
// To update multiple records:
// db.collection('users').updateMany(query, updateValues, callback);
4. Delete
Deleting is straightforward in MongoDB. Use deleteOne() to remove a specific document or deleteMany() to remove multiple documents.
Example:
javascript
// Delete a single document with name 'Alice'
db.collection('users').deleteOne({ name: "Alice" }, (err, res) => {
if (err) throw err;
console.log("Document deleted");
});
// To delete multiple documents:
// db.collection('users').deleteMany(query, callback);
Wrapping It Up
And there you have it! A quick but thorough look into CRUD operations in MongoDB. This is just the beginning of what you can do with MongoDB, but mastering these operations is a great stepping stone toward becoming comfortable with databases.
Practice Ideas
1. Create a Sample Project: Build a simple address book application where users can add contact details, view them, update when details change, or remove contacts they no longer need.
2. Experiment with Queries: Play around with different queries in MongoDB to fetch specific data with filters and projections.
3. Database Design: Think about how you can structure data in a MongoDB collection. Do some research on schema design for NoSQL databases.
Feel free to share your projects or questions with me or dive deeper into our other database-related tutorials. Happy coding, and until next time, keep experimenting and building awesome things!
If you’d like, head over to Open Source Images or Unsplash to find some relevant visuals to spice up your learning experience.
Thanks for reading, and I hope you now feel more empowered to use MongoDB in your applications. See you in the next tutorial! 🙌
