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):

javascript
{ acknowledged: true, insertedId: ObjectId("69e0a6a14d75051788b18e8e") }

Key points:

  • MongoDB automatically assigns a unique _id field (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:

javascript
{ acknowledged: true, insertedIds: [ ObjectId("69e0a6a14d75051788b18e8f"), ObjectId("69e0a6a14d75051788b18e90"), ObjectId("69e0a6a14d75051788b18e91") ] }

insertMany — Add Customers

Insert customer documents with nested preferences and arrays:

javascript
{ acknowledged: true, insertedIds: [ ObjectId("69e0a6a14d75051788b18e92"), ObjectId("69e0a6a14d75051788b18e93"), ObjectId("69e0a6a14d75051788b18e94") ] }

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:

javascript
// Returns all 100 products with all fields

find() with Filter — Products Under 500 KES

Use the $lt (less than) operator:

javascript
// Returns 25 products with price less than 500 KES (Bananas, Passion Fruit, Papaya, Grapes, Onions, etc.)

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:

javascript
// Returns one Dairy document (Fresh Milk 1L with all nested fields)

find() with AND Logic — Multiple Conditions

Find Fruits with stock 50 or more:

javascript
// Returns 9 fruits (Avocados, Bananas, Mangoes, Pineapple, Passion Fruit, etc.)

find() with Regex — Search by Pattern

Find all products containing "milk" (case-insensitive):

javascript
// Returns 3 documents (Fresh Milk 1L, Goat Milk 500ml, Fresh Milk 1L variant)

find() by City — Query Nested Fields

Find all customers in Nairobi:

javascript
// Returns 20 Nairobi customers (Sarah, Mary, and others)

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:

javascript
{ matchedCount: 1, modifiedCount: 1 }

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):

javascript
{ matchedCount: 1, modifiedCount: 1 }

Stock went from 8 to 3. $inc is atomic — perfect for handling concurrent updates.

updateMany — Update Multiple Documents

Mark all Nairobi customers as verified:

javascript
{ matchedCount: 20, modifiedCount: 20 }

Update Nested Field — Use Dot Notation

Change Priya's payment method inside preferences:

javascript
{ matchedCount: 1, modifiedCount: 1 }

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:

javascript
{ matchedCount: 1, modifiedCount: 1 }

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):

javascript
{ matchedCount: 1, modifiedCount: 1 }

$addToSet adds only if the value doesn't exist, preventing duplicate tags.

findOneAndUpdate — Return Updated Document

Update and get back the new document:

javascript
// Returns the complete Fresh Milk document with price: 135

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):

javascript
{ deletedCount: 1 }

deleteMany — Remove Multiple Documents

Delete all products with low stock (less than 10):

javascript
{ deletedCount: 3 }

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):

javascript
{ deletedCount: 2 }

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

javascript
// Returns: ObjectId("69e0a6a14d75051788b18e95")

Extract Timestamp from ObjectId

Get the creation time from the ObjectId:

javascript

Query by ObjectId

Find a product using its _id:

javascript
// Returns the Organic Avocados document

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:

javascript
// Products: 100 // Customers: 61

Test Your Knowledge

Question 1 of 5
What does insertMany return?
Question 2 of 5
How do you update a nested field like preferences.payment_method?
Question 3 of 5
What is the difference between updateOne and updateMany?
Question 4 of 5
What does the $inc operator do?
Question 5 of 5
Which bytes in an ObjectId contain the timestamp?
0
/5
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →