MongoDB is one of the most popular NoSQL databases used by developers today. Its flexible schema, ease of scaling, and JSON-like documents make it ideal for applications that need to handle large amounts of unstructured data. Mastering CRUD operations (Create, Read, Update, Delete) and conditional queries in MongoDB is fundamental for anyone working with this database.
In this guide, we’ll take you through the essential CRUD operations and query conditions using MongoDB. You’ll not only learn how to execute these operations, but we’ll also provide practical exercises and a sample dataset to work on. By the end of this post, you’ll be able to manage collections in MongoDB effectively and create powerful queries to retrieve exactly the data you need.
Ready to become a MongoDB pro? Let’s dive in!
1. Basic CRUD Operations in MongoDB 📚
CRUD stands for Create, Read, Update, and Delete, and it represents the four basic functions of persistent storage. Whether you’re working with a SQL or NoSQL database, these operations are critical to manipulating the data.
Create Operation (Insert Documents) 🛠️
The create operation in MongoDB is done using the insertOne() or insertMany() methods. These commands allow you to add new documents (records) into a collection (table).
Example:
js
// Insert a new document into the ‘books’ collection db.books.insertOne({ title: “The Great Gatsby”, author: “F. Scott Fitzgerald”, publishedYear: 1925 });
Explanation:
db.books refers to the collection named books.
insertOne() adds a single document to the collection. The document includes fields such as title, author, and publishedYear.
Read Operation (Retrieve Documents) 📖
Reading or retrieving documents from a MongoDB collection is done using the find() method. You can either retrieve all documents or use queries to filter the results.
Example:
js
// Retrieve all documents from the ‘books’ collection db.books.find();
// Retrieve documents with specific criteria
db.books.find({ author: “F. Scott Fitzgerald” });
Explanation:
The first query retrieves all documents in the books collection.
The second query retrieves documents where the author field is “F. Scott Fitzgerald”.
Update Operation (Modify Documents) 📝
To update existing documents in MongoDB, you use the updateOne() or updateMany() methods. These commands allow you to change specific fields in one or more documents.
Example:
js
// Update the publishedYear of ‘The Great Gatsby’ db.books.updateOne( { title: “The Great Gatsby” }, { $set: { publishedYear: 2023 } } );
Explanation:
The first part { title: “The Great Gatsby” } specifies the document to update.
The $set operator is used to modify the publishedYear field to 2023.
Delete Operation (Remove Documents) 🗑️
The deleteOne() or deleteMany() methods allow you to remove documents from a collection. You can specify conditions to delete specific documents or remove all documents at once.
Example:
js
// Delete a document from the ‘books’ collection where the title is “The Great Gatsby”
db.books.deleteOne({ title: “The Great Gatsby” });
Explanation:
- This deletes the document where the title is “The Great Gatsby”.
2. Query with Conditions in MongoDB 🔍
Queries are what make databases so powerful. In MongoDB, you can perform conditional queries to retrieve documents that meet specific criteria. These conditions are specified inside the find() method using a JSON-like format.
Query by Field Values 🎯
You can use the following operators to query by field values:
$lt for “less than”
$gt for “greater than”
$eq for “equal to”
$ne for “not equal to”
Example:
js
// Find all products where the price is less than 50 db.products.find({ price: { $lt: 50 } });
Explanation:
- This query retrieves all documents in the products collection where the price field is less than 50.
Query by Multiple Conditions (AND/OR) 🔗
You can combine multiple conditions using $and and $or operators to create more complex queries.
Example:
js
// Retrieve users where age is exactly 30 AND department is “Sales”
db.users.find({ $and: [ { age: 30 }, { department: “Sales” } ] });
Explanation:
This query retrieves documents from the users collection where the age is 30 and the department is “Sales”.
Query Arrays and Embedded Fields 📂
MongoDB allows you to query arrays and documents embedded inside other documents. This is extremely useful when dealing with more complex, hierarchical data.
Example:
js
// Find articles where the tags array includes ‘technology’ db.articles.find({ tags: “technology” });
Explanation:
This query finds all documents in the articles collection where the tags array contains “technology”.
3. Practical Exercises: Test Your MongoDB Skills 💪
Now that you’ve learned the basics, it’s time to put your knowledge into practice. Below are some practical exercises for you to work on. These will help you solidify your understanding of MongoDB CRUD operations and queries.
Exercise 1: Create and Manage an Inventory Collection 🛒
- Create a collection called inventory and add the following fields to each document: item, quantity, price, and status.
Example:
js
db.inventory.insertMany([ { item: “laptop”, quantity: 50, price: 1000, status: “available” }, { item: “phone”, quantity: 30, price: 500, status: “sold out” }, { item: “monitor”, quantity: 25, price: 150, status: “available” } ]);
- Query to retrieve all items where the price is greater than 400.
Example:
js
db.inventory.find({ price: { $gt: 400 } });
Update the quantity of laptop to 45.
Example:
js
db.inventory.updateOne( { item: “laptop” }, { $set: { quantity: 45 } } );
Delete the phone record from the inventory.
Example:
js
db.inventory.deleteOne({ item: “phone” });
Solution Explanation:
Step 1: We create three documents in the inventory collection using insertMany().
Step 2: We query the inventory collection to find all items where the price is greater than 400.
Step 3: We update the quantity of the laptop from 50 to 45 using the $set operator.
Step 4: We delete the document with the item name “phone”.
Exercise 2: Manage an Employees Collection 👨💼👩💼
Create a new employees collection with fields name, age, department, and salary.
Example:
js
db.employees.insertMany([ { name: “Alice”, age: 28, department: “HR”, salary: 55000 }, { name: “Bob”, age: 35, department: “Engineering”, salary: 75000 }, { name: “Charlie”, age: 40, department: “Sales”, salary: 65000 } ]);
Query to find all employees in the “Engineering” department.
Example:
js
db.employees.find({ department: “Engineering” });
Increase the salary of Bob to 80000.
Example:
js
db.employees.updateOne( { name: “Bob” }, { $set: { salary: 80000 } } );
Delete the employee Charlie from the collection.
Example:
js
db.employees.deleteOne({ name: “Charlie” });
Solution Explanation:
Step 1: We insert multiple employee documents into the employees collection.
Step 2: We query the collection to find employees where the department is “Engineering”.
Step 3: We update Bob’s salary using the $set operator.
Step 4: We delete the document where name is “Charlie”.
4. Sample MongoDB Collection and Query Breakdown 📊
Below is a sample collection of employees along with a practical query to retrieve data.
js
// Sample ’employees’ collection
db.employees.insertMany([ { name: “Alice”, age: 28, department: “HR”, salary: 55000 }, { name: “Bob”, age: 35, department: “Engineering”, salary: 75000 }, { name: “Charlie”, age: 40, department: “Sales”, salary: 65000 } ]);
// Query to find employees earning more than 60,000 db.employees.find({ salary: { $gt: 60000 } });
Explanation:
-
Collection Structure: The employees collection contains fields like name, age, department, and salary.
-
Query Logic: The query retrieves all employees whose salary is greater than 60,000.
5. Conclusion: Why Mastering CRUD Operations in MongoDB is Essential 🏆
Congratulations! 🎉 You’ve just learned how to perform CRUD operations and run conditional queries in MongoDB. These operations form the core of managing any MongoDB database. Whether you’re working on an e-commerce platform, a social media app, or a data-driven website, these skills will allow you to manage your data efficiently.
Now it’s time to practice! Use the exercises provided and try creating your own MongoDB collections and queries. Remember, practice makes perfect, and the more you work with these concepts, the more intuitive they will become.
Good luck with your MongoDB journey! 💻🚀