CRUD Operations
40 minCRUD operations (Create, Read, Update, Delete) are the fundamental operations for working with MongoDB data. MongoDB provides intuitive methods for each operation, with variations for single and multiple document operations. Understanding CRUD operations is essential for interacting with MongoDB collections. Each operation supports various options for filtering, projection, and modification, enabling flexible data manipulation.
Create operations insert new documents into collections. insertOne() inserts a single document, while insertMany() inserts multiple documents in a single operation. MongoDB automatically generates an _id field (ObjectId) if not provided. Insert operations are atomic at the document level, and insertMany() can be ordered (stops on first error) or unordered (continues after errors). Understanding insert behavior helps you handle errors and optimize bulk operations.
Read operations query documents from collections. find() returns a cursor to all matching documents, while findOne() returns a single document. Query filters use operators like $eq, $gt, $lt, $in, $and, $or for complex conditions. Projection limits returned fields, improving performance by reducing data transfer. Understanding query operators and projection enables efficient data retrieval.
Update operations modify existing documents. updateOne() updates the first matching document, while updateMany() updates all matching documents. Update operators like $set (set field values), $inc (increment numeric values), $push (add to arrays), and $pull (remove from arrays) enable precise modifications. replaceOne() replaces entire documents. Understanding update operators enables efficient data modifications.
Delete operations remove documents from collections. deleteOne() removes the first matching document, while deleteMany() removes all matching documents. Delete operations are permanent and cannot be undone, so careful filtering is essential. Understanding delete operations and their implications helps you manage data lifecycle safely.
Best practices for CRUD operations include using appropriate methods (single vs multiple), understanding atomicity guarantees, using indexes for query performance, and handling errors appropriately. MongoDB operations are atomic at the document level, meaning all changes to a single document succeed or fail together. Understanding atomicity and transaction boundaries helps you design reliable applications.
Key Concepts
- CRUD operations are fundamental to MongoDB data manipulation.
- insertOne/insertMany create documents, find/findOne read documents.
- updateOne/updateMany modify documents using update operators.
- deleteOne/deleteMany remove documents from collections.
- Query operators enable complex filtering conditions.
Learning Objectives
Master
- Performing Create, Read, Update, and Delete operations
- Using query operators for filtering documents
- Understanding update operators for modifying documents
- Applying projection to limit returned fields
Develop
- Understanding MongoDB data manipulation patterns
- Designing efficient query patterns
- Implementing safe data modification operations
Tips
- Use findOne() for single document queries: faster than find().limit(1).
- Use projection to limit fields: db.collection.find({}, { name: 1, email: 1 }).
- Use $set for updates: db.collection.updateOne({}, { $set: { field: value } }).
- Use $inc for numeric increments: db.collection.updateOne({}, { $inc: { count: 1 } }).
Common Pitfalls
- Using updateOne without $set, replacing entire documents unintentionally.
- Not using projection, transferring unnecessary data.
- Using deleteMany without filters, accidentally deleting all documents.
- Not understanding query operator syntax, writing incorrect queries.
Summary
- CRUD operations enable all data manipulation in MongoDB.
- Query operators enable complex filtering and data retrieval.
- Update operators enable precise document modifications.
- Understanding CRUD operations is essential for MongoDB development.
Exercise
Perform all CRUD operations on a collection.
// CREATE - Insert documents
db.customers.insertOne({
name: "Alice Johnson",
email: "alice@example.com",
age: 25,
membership: "premium"
})
db.customers.insertMany([
{ name: "Bob Smith", email: "bob@example.com", age: 30, membership: "basic" },
{ name: "Carol Davis", email: "carol@example.com", age: 35, membership: "premium" }
])
// READ - Query documents
// Find all documents
db.customers.find()
// Find specific document
db.customers.findOne({ name: "Alice Johnson" })
// Find with conditions
db.customers.find({ age: { $gte: 30 } })
// Find with multiple conditions
db.customers.find({
age: { $gte: 25 },
membership: "premium"
})
// Projection - select specific fields
db.customers.find({}, { name: 1, email: 1, _id: 0 })
// UPDATE - Update documents
// Update one document
db.customers.updateOne(
{ name: "Alice Johnson" },
{ $set: { age: 26, updatedAt: new Date() } }
)
// Update multiple documents
db.customers.updateMany(
{ membership: "basic" },
{ $set: { membership: "standard" } }
)
// Increment a field
db.customers.updateOne(
{ name: "Bob Smith" },
{ $inc: { age: 1 } }
)
// DELETE - Remove documents
// Delete one document
db.customers.deleteOne({ name: "Carol Davis" })
// Delete multiple documents
db.customers.deleteMany({ membership: "basic" })
// Delete all documents (be careful!)
// db.customers.deleteMany({})
Exercise Tips
- Use $in for multiple values: db.collection.find({ field: { $in: [value1, value2] } }).
- Use $and and $or for complex conditions: db.collection.find({ $or: [{ field1: value1 }, { field2: value2 }] }).
- Use $push to add to arrays: db.collection.updateOne({}, { $push: { arrayField: value } }).
- Use $pull to remove from arrays: db.collection.updateOne({}, { $pull: { arrayField: value } }).