Insert Operations
MongoDB stores data as documents (JSON-like objects) inside collections (similar to tables). Inserting data is the first CRUD operation.
insertOne — Add a Single Product
Create a single document with nested fields (supplier info, nutrition, tags):
Key points:
- MongoDB automatically assigns a unique
_idfield (the primary key). - Nested objects (like
supplier) are stored directly in the document — no JOIN needed. - Arrays (like
tags) store multiple values in one field.
insertMany — Add Multiple Products
Insert three products at once:
insertMany — Add Customers
Insert customer documents with nested preferences and arrays:
Notice: Documents in MongoDB can have different structures. Sarah has dietary as an array, while the structure is flexible. This is the power of the document model — no fixed schema.
Read Operations
Query documents using find() with filters. No complex JOINs needed — nested data is already there.
find() — Get All Products
Retrieve every document in the products collection:
find() with Filter — Products Under 500 KES
Use the $lt (less than) operator:
Common comparison operators: $lt (less than), $lte (≤), $gt (greater than), $gte (≥), $eq (equals), $ne (not equal).
findOne() — Get a Single Document
Find the first Dairy product:
find() with AND Logic — Multiple Conditions
Find Fruits with stock 50 or more:
find() with Regex — Search by Pattern
Find all products containing "milk" (case-insensitive):
find() by City — Query Nested Fields
Find all customers in Nairobi:
Update Operations
Modify documents using atomic operators. MongoDB operators start with $ and allow precise updates.
updateOne with $set — Change a Field
Increase the price of Fresh Milk:
The $set operator replaces or adds a field without touching other fields.
updateOne with $inc — Increment a Number
Decrease stock after a sale (use negative number):
Stock went from 8 to 3. $inc is atomic — perfect for handling concurrent updates.
updateMany — Update Multiple Documents
Mark all Nairobi customers as verified:
Update Nested Field — Use Dot Notation
Change Priya's payment method inside preferences:
Dot notation (preferences.payment_method) lets you update nested fields without rewriting the parent object.
$push — Add Item to Array
Add a tag to Basmati Rice:
The tags array now includes "bulk-buy". Use $push to add duplicates.
$addToSet — Add Unique Item to Array
Add "seasonal" tag to Alphonso Mangoes (only if not already there):
$addToSet adds only if the value doesn't exist, preventing duplicate tags.
findOneAndUpdate — Return Updated Document
Update and get back the new document:
Use returnDocument: "after" to see the updated state, or "before" for the old state.
Delete Operations
Remove documents from a collection. Deletes are permanent — no undo!
deleteOne — Remove a Single Document
Delete Chai Masala (stock was too low anyway):
deleteMany — Remove Multiple Documents
Delete all products with low stock (less than 10):
3 products were deleted. Always be careful with deleteMany — it matches all documents satisfying the condition.
deleteMany with Complex Condition
Remove inactive customers (who haven't placed any orders):
WARNING: Deletes are immediate and permanent. Always test your filter with find() first to ensure you're deleting the right documents.
Understanding ObjectId
MongoDB's ObjectId is a unique identifier automatically assigned to every document. It's not just a number — it's a 12-byte structure containing useful information.
ObjectId Structure (12 Bytes)
An ObjectId is composed of:
- Bytes 0-3 (Timestamp) — Seconds since Unix epoch (1970-01-01). Extract creation time from the ID itself.
- Bytes 4-6 (Machine ID) — Identifier of the machine/server that created the ID.
- Bytes 7-8 (Process ID) — Process ID on that machine.
- Bytes 9-11 (Counter) — Auto-incrementing counter, unique per process.
Together, these guarantee uniqueness across all MongoDB instances — no coordination needed!
Generate an ObjectId Manually
Extract Timestamp from ObjectId
Get the creation time from the ObjectId:
Query by ObjectId
Find a product using its _id:
This is the fastest query type — MongoDB indexes the _id field automatically.
Verify All CRUD Operations
Count products and customers after all inserts, updates, and deletes:
Test Your Knowledge
CRUD mastered. You speak MongoDB.
Join the Best AI Program: The AI-Era Data Engineer — 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Data Engineer →