Title: CRUD Operations in MongoDB
This chapter focuses on mastering CRUD (Create, Read, Update, Delete) operations in MongoDB. These are the foundational operations used to interact with and manipulate data within a MongoDB database. Understanding CRUD operations is crucial for any developer aiming to efficiently manage and query data in MongoDB, especially at the FAANG level, where data manipulation efficiency and correctness are paramount.
1. Creating Documents with Insert
Notes:
-
Insert Operations: In MongoDB, the
insertoperations are used to add new documents to a collection. There are two main methods for inserting documents:insertOne(): Inserts a single document into a collection.insertMany(): Inserts multiple documents into a collection at once.
-
insertOne():- Accepts a single document to be inserted into the specified collection.
- Automatically adds an
_idfield to the document if it is not provided. The_idserves as a unique identifier for the document within the collection.
-
insertMany():- Accepts an array of documents to be inserted into the specified collection.
- Provides options for handling errors and enabling ordered or unordered inserts.
Example:
// Insert a single document
db.users.insertOne({
name: "Bob",
age: 25,
email: "bob@example.com",
});
// Insert multiple documents
db.users.insertMany([
{
name: "Alice",
age: 30,
email: "alice@example.com",
},
{
name: "Charlie",
age: 35,
email: "charlie@example.com",
},
]);
- Ordered vs. Unordered Inserts:
- Ordered Inserts: MongoDB stops the insert operation when an error occurs (default behavior).
- Unordered Inserts: MongoDB continues inserting documents even if some documents cause errors.
Example:
db.users.insertMany(
[
{ name: "David", age: 40 },
{ name: "Eve", age: "invalid_age" }, // This will cause an error
],
{ ordered: false }
);
2. Reading Documents with Find
Notes:
-
Read Operations: MongoDB provides several methods to query and retrieve documents from a collection:
find(): Retrieves all documents that match a query filter.findOne(): Retrieves a single document that matches a query filter.
-
find():- Takes an optional query filter object to specify criteria for selecting documents.
- Supports a wide range of query operators, such as
$gt,$lt,$eq,$ne,$in, and more. - Can be combined with projection operators to return only specific fields.
Example:
// Retrieve all users
db.users.find();
// Retrieve users older than 30
db.users.find({ age: { $gt: 30 } });
// Retrieve users and return only their name and email
db.users.find({}, { name: 1, email: 1, _id: 0 });
findOne():- Similar to
find(), but returns only the first document that matches the query criteria.
- Similar to
Example:
// Retrieve a single user with the name 'Alice'
db.users.findOne({ name: "Alice" });
3. Updating Documents with Update
Notes:
-
Update Operations: MongoDB provides several methods for modifying existing documents in a collection:
updateOne(): Updates a single document that matches a query filter.updateMany(): Updates multiple documents that match a query filter.replaceOne(): Replaces a single document that matches a query filter with a new document.
-
updateOne()andupdateMany():- Use the
$setoperator to modify specific fields within documents. - Support other update operators, such as
$inc(increment),$unset(remove field),$push(add to array),$pull(remove from array), and more.
- Use the
Example:
// Update the age of a single user
db.users.updateOne({ name: "Bob" }, { $set: { age: 26 } });
// Increment the age of all users by 1
db.users.updateMany({}, { $inc: { age: 1 } });
replaceOne():- Replaces an entire document, which is useful when you want to completely overwrite a document's contents.
Example:
// Replace a user's document entirely
db.users.replaceOne(
{ name: "Alice" },
{ name: "Alice", age: 31, email: "alice@newdomain.com" }
);
4. Deleting Documents with Delete
Notes:
-
Delete Operations: MongoDB provides methods for removing documents from a collection:
deleteOne(): Deletes a single document that matches a query filter.deleteMany(): Deletes all documents that match a query filter.
-
deleteOne():- Removes the first document that matches the query criteria.
-
deleteMany():- Removes all documents that match the query criteria.
Example:
// Delete a single user with the name 'Charlie'
db.users.deleteOne({ name: "Charlie" });
// Delete all users older than 30
db.users.deleteMany({ age: { $gt: 30 } });
5. Handling Errors and Validations
Notes:
-
Error Handling: Proper error handling is crucial for robust application development. MongoDB operations can fail due to various reasons such as network errors, duplicate key errors, or validation errors.
-
Common Error Types:
- Duplicate Key Error: Occurs when a document with a duplicate value for a field with a unique index is inserted or updated.
- Validation Error: Occurs when a document fails to meet the schema validation criteria.
-
Handling Errors in CRUD Operations:
- Use try-catch blocks to handle errors in Node.js or any other application framework.
- Use MongoDB’s write concern to specify the level of acknowledgment required from MongoDB after an operation.
Example:
try {
db.users.insertOne({ _id: 1, name: "John" });
db.users.insertOne({ _id: 1, name: "Jane" }); // This will cause a duplicate key error
} catch (e) {
console.error("Error inserting documents:", e.message);
}
Conclusion
This chapter provides a comprehensive overview of CRUD operations in MongoDB, which are the fundamental building blocks for managing data within MongoDB databases. Mastery of these operations is essential for efficiently and effectively managing data in MongoDB, aligning with the expectations of top tech companies. The next chapters will build upon these basics and introduce more advanced MongoDB functionalities.