CRUD Operations
CRUD Operations
In MongoDB, CRUD operations allow you to manage the lifecycle of documents within your collections. Unlike relational databases, MongoDBβs schema flexibility allows documents in the same collection to have different fields.
ποΈ 1. Create (Insert)
Creation operations add new documents to a collection. If the collection does not exist, the insert operation will create it.
Mongo Shell
// Insert a single document
db.users.insertOne({
name: "Alice",
age: 28,
email: "alice@example.com",
tags: ["developer", "mongodb"]
});
// Insert multiple documents
db.users.insertMany([
{ name: "Bob", age: 32, email: "bob@example.com" },
{ name: "Charlie", age: 25, email: "charlie@example.com" }
]);PyMongo
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]
users = db["users"]
# Insert One
users.insert_one({"name": "Alice", "age": 28})
# Insert Many
users.insert_many([
{"name": "Bob", "age": 32},
{"name": "Charlie", "age": 25}
])π 2. Read (Find)
Reading operations retrieve documents from a collection.
Mongo Shell
// Find all documents
db.users.find({});
// Find with a filter
db.users.find({ age: { $gt: 30 } });
// Projecting specific fields (1 = include, 0 = exclude)
db.users.find({ name: "Alice" }, { email: 1, _id: 0 });PyMongo
# Find One
user = users.find_one({"name": "Alice"})
# Find Many (Returns a Cursor)
for user in users.find({"age": {"$gt": 30}}):
print(user)β‘ 3. Update
Update operations modify existing documents. MongoDB provides atomic operators to update fields without replacing the entire document.
Mongo Shell
// Update a single document using $set
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 29 } }
);
// Incrementing a value with $inc
db.users.updateOne(
{ name: "Alice" },
{ $inc: { login_count: 1 } }
);PyMongo
# Update One
users.update_one({"name": "Alice"}, {"$set": {"age": 29}})
# Update Many
users.update_many({"age": {"$lt": 30}}, {"$set": {"status": "junior"}})π 4. Delete
Delete operations remove documents from a collection.
Mongo Shell
// Delete a single document
db.users.deleteOne({ name: "Charlie" });
// Delete many based on criteria
db.users.deleteMany({ age: { $lt: 18 } });PyMongo
# Delete One
users.delete_one({"name": "Charlie"})
# Delete Many
users.delete_many({"status": "inactive"})π‘ Best Practices
- Use Atomic Operators: Always prefer
$set,$inc,$push, etc., to minimize network overhead and ensure data integrity. - Limit Result Sets: When reading, use
.limit()and.skip()for pagination to avoid loading massive amounts of data into memory. - Projection: Only fetch the fields you need (
find({}, {field: 1})) to reduce I/O and memory usage. - Bulk Operations: Use
bulkWritewhen performing thousands of operations to significantly improve performance by reducing round-trips.