Lab 11: MongoDB CRUD

Time: 40 minutes | Level: Practitioner | DB: MongoDB 7

MongoDB stores data as BSON documents (like JSON) in collections. Unlike SQL rows, documents are schema-flexible — each can have different fields. This lab covers all CRUD operations with mongosh.


Step 1 — Setup: Connect and Create Collection

# Start MongoDB
docker run -d --name mongo-lab mongo:7
sleep 5
docker exec -it mongo-lab mongosh
// Select (or create) a database
use shopdb

// MongoDB creates the database and collection
// on first insert — no CREATE TABLE needed
db.products.drop()  // clean start if re-running

💡 MongoDB databases and collections are created lazily — they don't exist until you insert a document. use shopdb just sets the current database context.


Step 2 — insertOne and insertMany

// insertOne: single document
let r1 = db.products.insertOne({
  name:     "Laptop Pro",
  category: "Electronics",
  price:    1299.99,
  stock:    50,
  tags:     ["laptop", "portable", "premium"],
  specs:    { ram: "16GB", storage: "512GB SSD", weight: "1.4kg" },
  isActive: true
})
print("Inserted ID:", r1.insertedId)

📸 Verified Output:


Step 3 — findOne and find with Filters

📸 Verified Output:


Step 4 — Comparison and Logical Operators

📸 Verified Output (price < 50):

💡 MongoDB field names are case-sensitive. { Name: "Laptop" } will NOT match a document with { name: "Laptop" }.


Step 5 — Projection, Sort, Skip, Limit


Step 6 — updateOne and updateMany

📸 Verified Output:


Step 7 — deleteOne, deleteMany, and findOneAndUpdate


Step 8 — Capstone: Product Catalog CRUD Application


Summary

Operation
Command
Filter Example

Insert one

insertOne({...})

Insert many

insertMany([...])

Find one

findOne({field: val})

{ price: { $lt: 50 } }

Find many

find({}).sort().limit()

{ $or: [{a:1},{b:2}] }

Update one

updateOne(filter, {$set:{}})

Uses $set, $inc, $push

Update many

updateMany(filter, update)

Same operators

Delete one

deleteOne(filter)

Any filter

Delete many

deleteMany(filter)

Any filter

Atomic update

findOneAndUpdate(f, u, opts)

returnDocument: "after"

Upsert

updateOne(f, u, {upsert:true})

Inserts if not found

Last updated