Showing posts with label NoSQL Database. Show all posts
Showing posts with label NoSQL Database. Show all posts

MongoDB Update & Delete Made Easy: Step-by-Step for Beginners


Updating and Deleting Data in MongoDB

A Magical Eraser & Pencil Adventure - For Beginner to Expert Level

Imagine you have a super-smart notebook where you can change a drawing with a magic pencil or erase it with a magic eraser — without messing up the whole page! In MongoDB, updating means changing data, and deleting means removing it. This tutorial is a fun art class, super easy for beginners, but full of pro secrets for experts.

We’ll use:

  • Our Hero Academy from before
  • mongosh (command line)
  • MongoDB Compass (click & edit)
  • Real images
  • Beginner → Expert tips

Let’s grab the pencil and eraser!


Table of Contents

  1. Part 1: Sample Data (Your Hero Notebook)
  2. Part 2: Updating Data: The Magic Pencil
  3. Part 3: Deleting Data: The Magic Eraser
  4. Part 4: Using Compass: Click to Edit & Delete
  5. Part 5: Pro Update Operators (Expert Level)
  6. Part 6: Mini Project: Hero Academy Management!
  7. Part 7: Safety First (Important Rules)
  8. Part 8: Pro Tips for All Levels
  9. Part 9: Cheat Sheet
  10. Part 10: Common Mistakes & Fixes
  11. When to Use updateMany vs bulkWrite
  12. Error Handling Examples


Part 1: Sample Data (Your Hero Notebook)

Run this in mongosh (or skip if you have data):

use heroAcademy
db.heroes.insertMany([
  { name: "Aarav", power: "Super Speed", level: 5, isActive: true, team: "Alpha" },
  { name: "Priya", power: "Invisibility", level: 7, isActive: true, team: "Alpha" },
  { name: "Rohan", power: "Fire Control", level: 4, isActive: false, team: "Beta" },
  { name: "Sanya", power: "Telekinesis", level: 6, isActive: true, team: "Beta" },
  { name: "Karan", power: "Ice Blast", level: 3, isActive: true, team: "Alpha" }
])


Part 2: Updating Data: The Magic Pencil

1. updateOne – Change One Hero

db.heroes.updateOne(
  { name: "Aarav" },                    // Filter: Find Aarav
  { $set: { level: 6, isActive: true } } // Change: level → 6
)

Output:

{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }

Beginner Win: Aarav got promoted!
matchedCount: Found 1 hero
modifiedCount: Actually changed 1

updateOne → silent update. findOneAndUpdate → returns old/new doc.

2. updateMany - Change Many Heroes

db.heroes.updateMany(
  { team: "Alpha" },                    // All Alpha team
  { $set: { uniform: "Blue" } }         // Add uniform
)

Result: Aarav, Priya, Karan now have "uniform": "Blue"

3. $inc – Increase Numbers

db.heroes.updateOne(
  { name: "Priya" },
  { $inc: { level: 1 } }
)

→ Priya’s level: 7 → 8
Like: Giving +1 star for good work!

4. $push – Add to Array

db.heroes.updateOne(
  { name: "Sanya" },
  { $push: { skills: "mind control" } }
)

→ Sanya’s skills: ["lift", "fly"] → ["lift", "fly", "mind control"]

5. $pull – Remove from Array

db.heroes.updateOne(
  { name: "Sanya" },
  { $pull: { skills: "fly" } }
)

→ Removes "fly" from skills

6. replaceOne – Replace Entire Hero

db.heroes.replaceOne(
  { name: "Karan" },
  {
    name: "Karan",
    power: "Ice Storm",
    level: 5,
    isActive: true,
    team: "Alpha",
    newPower: true
  }
)

Warning: Replaces everything — old fields like skills are gone!



Part 3: Deleting Data: The Magic Eraser

In this part, you'll learn how to safely remove data from one document to the entire database.

1. deleteOne – Erase One Hero

db.heroes.deleteOne({ name: "Rohan" })

→ Rohan is gone!

2. deleteMany – Erase Many Heroes

db.heroes.deleteMany({ isActive: false })

→ All inactive heroes erased!

3. Delete Entire Collection

db.heroes.drop()

→ Whole heroes shelf gone!

4. Delete Entire Database

db.dropDatabase()

→ Whole heroAcademy toy box gone! Be careful!



Part 4: Using Compass: Click to Edit & Delete

Step 1: Open Compass → heroAcademy → heroes

Step 2: Edit with Click

Click on Priya’s row
Click pencil icon
Change level: 8 → 9
Click Update

Compass Edit

Step 3: Delete with Click

Hover over a hero
Click trash icon
Confirm Delete

Beginner Magic: No typing. Just click.



Part 5: Pro Update Operators (Expert Level)

OperatorUseExample
$setSet a field{ $set: { team: "Gamma" } }
$unsetRemove a field{ $unset: { uniform: "" } }
$renameRename a field{ $rename: { level: "rank" } }
$pushAdd to array{ $push: { skills: "laser" } }
$addToSetAdd only if not exists{ $addToSet: { skills: "fly" } }
$popRemove first/last from array{ $pop: { skills: 1 } }
$incIncrease number{ $inc: { level: 2 } }


Part 6: Mini Project: Hero Academy Management

Let’s run a real school!

1. Promote All Active Alpha Heroes

db.heroes.updateMany(
  { team: "Alpha", isActive: true },
  { $inc: { level: 1 }, $set: { badge: "Gold" } }
)

2. Add New Skill to Top Hero

db.heroes.updateOne(
  { level: { $gte: 8 } },
  { $push: { skills: "leadership" } }
)

3. Remove Inactive Heroes

db.heroes.deleteMany({ isActive: false })

4. Clean Up Old Uniforms

db.heroes.updateMany(
  {},
  { $unset: { uniform: "" } }
)


Part 7: Safety First (Important Rules)

RuleWhy It Matters
Always use filterPrevent updating/deleting everything
Test with find() firstSee what will change
Backup before drop()No undo!
Use updateOne for single editsSafer than updateMany


Part 8: Pro Tips for All Levels

For Students & Beginners

  • Use Compass to click and change
  • Start with updateOne
  • Make a "Pet Diary" – update pet age!

For Medium Learners

Use upsert (update or insert):

db.heroes.updateOne(
  { name: "New Hero" },
  { $set: { power: "Light" } },
  { upsert: true }
)

→ Creates if not found!

Return updated document:

db.heroes.findOneAndUpdate(
  { name: "Priya" },
  { $inc: { level: 1 } },
  { returnNewDocument: true }
)

For Experts

Use pipeline updates (MongoDB 4.2+):

db.heroes.updateOne(
  { name: "Sanya" },
  [
    { $set: { level: { $add: ["$level", 1] } } },
    { $set: { status: { $cond: [ { $gte: ["$level", 10] }, "Master", "Hero" ] } } }
  ]
)

Atomic updates with transactions:

const session = db.getMongo().startSession()
session.startTransaction()
// ... updates
session.commitTransaction()


When to Use updateMany vs bulkWrite

Use updateMany when:

  • You want to apply the same update to multiple documents.
  • You only need one filter and one update definition.
  • You don’t need per-document custom updates.
  • You want a simple operation with minimal complexity.
db.heroes.updateMany(
  { isActive: true },
  { $inc: { level: 1 } }
)

Use bulkWrite when:

  • You want to perform different updates on different documents.
  • You need high performance when applying thousands of operations.
  • You want multiple operation types (insert, update, delete) in one batch.
  • You need fine-grained control over each write.
db.heroes.bulkWrite([
  {
    updateOne: {
      filter: { name: "Aarav" },
      update: { $inc: { level: 1 } }
    }
  },
  {
    updateOne: {
      filter: { team: "Alpha" },
      update: { $set: { uniform: "Blue" } }
    }
  },
  {
    deleteOne: {
      filter: { isActive: false }
    }
  }
])

Summary:
updateMany → simple, one-update-to-all
bulkWrite → complex, different operations in one batch



Error Handling Examples (Important)

1. What happens when a filter matches 0 documents?

If your filter does not match anything, MongoDB will NOT throw an error. It simply returns:

{
  acknowledged: true,
  matchedCount: 0,
  modifiedCount: 0
}

Example:

db.heroes.updateOne(
  { name: "NonExistingHero" },
  { $set: { level: 99 } }
)

Good practice: Always check matchedCount.

const result = db.heroes.updateOne(...)

if (result.matchedCount === 0) {
  print("⚠ No hero found with that filter!")
}

2. What if you use deleteOne with a non-matching filter?

Result:

{ acknowledged: true, deletedCount: 0 }

3. What if update operation is malformed?

Example of incorrect update (missing $ operator):

db.heroes.updateOne(
  { name: "Aarav" },
  { level: 20 }   // ❌ wrong
)

This throws:

MongoServerError: The update operation document must contain atomic operators

4. How to safely test updates?

Always run a preview first:

db.heroes.find({ team: "Alpha" })

This prevents accidental mass updates.



Part 9: Cheat Sheet (Print & Stick!)

CommandWhat It Does
updateOne(filter, update)Change 1 document
updateMany(filter, update)Change many
$set: { field: value }Set field
$inc: { field: 1 }Increase number
$push: { array: value }Add to array
deleteOne(filter)Delete 1
deleteMany(filter)Delete many
drop()Delete collection


Part 10: Common Mistakes & Fixes

MistakeFix
Forgetting $setAlways use $set to change fields
Using = instead of $setWrong! Use { $set: { level: 6 } }
No filter → updates allAlways add { name: "X" }
drop() by mistakeNo undo! Backup first


Final Words

You’re a Data Artist!

You just:

  • Used pencil (updateOne, $set, $inc)
  • Used eraser (deleteOne, drop)
  • Edited in shell and GUI
  • Learned pro tricks like upsert, pipelines


Your Mission:

db.heroes.updateOne(
  { name: "You" },
  { $set: { power: "MongoDB Master", level: 100 } },
  { upsert: true }
)


Your Task:

"Add a new power to all heroes with level >= 6 and remove inactive ones."

You just added yourself as a hero!
You’re now a Certified MongoDB Editor!

Resources



Before You Leave : Become a MongoDB Hero

If this tutorial helped you:

  • Share it with a friend learning databases
  • Leave a comment below
  • Bookmark this post for quick reference


Want more lessons? Tell me in the comments what you want next:

  • MongoDB Aggregation
  • Joins & Lookup
  • Indexing for Speed
  • Real World MongoDB Projects

Stay curious, hero. Your MongoDB journey has just begun. ⚡

Keep drawing in your magic notebook.


Other Resources

Inserting Documents in MongoDB: insertOne & insertMany


Inserting Documents in MongoDB: insertOne & insertMany

A Magical, Fun, and Super-Powerful Guide for Beginner to Expert Level

Imagine you have a magic diary that grows bigger every time you write in it. You can add one secret at a time or a whole page of secrets in one go. In MongoDB, inserting documents means adding new entries (called documents) into your collection. This tutorial teaches you how to use insertOne and insertMany in the easiest way to a student but with deep pro tips for experienced coders.

Let’s write in the magic diary.


๐Ÿ“– Table of Contents


Part 1: What is a Document?

A document = One complete entry in MongoDB. It’s like one student’s full profile in a school register.

{
  "name": "Aarav",
  "power": "Super Speed",
  "level": 5,
  "isActive": true,
  "skills": ["running", "jumping", "flying"]
}

Think of it as: A sticky note with all info about one superhero!


๐Ÿง  Visual Snapshot: How MongoDB Stores Documents

Think of MongoDB like a folder system:

  • Database → like a school.
  • Collection → a class register.
  • Document → one student’s profile (JSON object).

Each document can have different fields. MongoDB is schema-flexible, meaning not all documents need the same structure.

Database: heroAcademy
└── Collection: heroes
    ├── Document 1 → Aarav
    ├── Document 2 → Priya
    └── Document 3 → Rohan

Part 2: Method 1 : Using mongosh (The Command Way)

Step 1: Open mongosh

Open terminal (Linux/macOS) or Command Prompt (Windows):

mongosh

You’ll see:

test>

Step 2: Switch to Your Database

use heroAcademy

Magic: If heroAcademy doesn’t exist, MongoDB creates it when you add data!

Step 3: insertOne - Add One Hero

db.heroes.insertOne({
  name: "Aarav",
  power: "Super Speed",
  level: 5,
  isActive: true,
  joined: ISODate("2025-01-15"),
  skills: ["running", "jumping"]
})

Output:

{
  acknowledged: true,
  insertedId: ObjectId("671a7f3d8e4b2c1f9d5e7a4e")
}

Beginner Win: You just added one hero to the heroes collection! The collection is created automatically.

Step 4: insertMany : Add Many Heroes at Once!

db.heroes.insertMany([
  {
    name: "Priya",
    power: "Invisibility",
    level: 7,
    isActive: true,
    joined: ISODate("2025-02-20"),
    skills: ["hiding", "sneaking", "reading minds"]
  },
  {
    name: "Rohan",
    power: "Fire Control",
    level: 4,
    isActive: false,
    joined: ISODate("2025-03-10"),
    skills: ["flame ball", "heat shield"]
  },
  {
    name: "Sanya",
    power: "Telekinesis",
    level: 6,
    isActive: true,
    joined: ISODate("2025-01-30"),
    skills: ["lifting", "flying objects"]
  }
])

Output:

{
  acknowledged: true,
  insertedIds: [
    ObjectId("671a7f5e..."),
    ObjectId("671a7f5e..."),
    ObjectId("671a7f5e...")
  ]
}

Beginner Example: You just filled 3 pages of your diary in one go!

Step 5: See Your Heroes!

db.heroes.find().pretty()

Output (pretty view):

{
  "_id": ObjectId("671a7f3d..."),
  "name": "Aarav",
  "power": "Super Speed",
  ...
}

Part 3: Method 2 : Using MongoDB Compass (Click & Add!)

Step 1: Open Compass

Download: mongodb.com/compass

Step 2: Connect

Connection: mongodb://localhost:27017
Click Connect

Step 3: Add One Hero with Clicks

Go to heroAcademy → heroes
Click "ADD DATA" → "Insert Document"

{
  "name": "Karan",
  "power": "Ice Blast",
  "level": 3,
  "isActive": true,
  "skills": ["freezing", "snowball"]
}

Beginner Magic: No typing! Just paste and click!

Step 4: Add Many with Import

Save this as heroes.json:

[
  { "name": "Neha", "power": "Healing", "level": 8, "skills": ["cure", "shield"] },
  { "name": "Vikram", "power": "Strength", "level": 9, "skills": ["lift", "punch"] }
]

In Compass → heroes → "ADD DATA" → "Import File"
Select heroes.json → Import

Pro Win: Import thousands of heroes in seconds!


Part 4: insertOne vs insertMany : The Big Difference

FeatureinsertOneinsertMany
Adds1 documentMany documents (array)
SpeedGood for singleFaster for bulk
Error HandlingStops on errorContinues (unless ordered: false)
ReturnsOne _idArray of _ids
Best ForAdding one userUploading CSV, logs, seed data

Part 5: Pro Features of insertMany

1. Ordered vs Unordered

db.heroes.insertMany(
  [doc1, doc2, doc3],
  { ordered: false }
)

ordered: true (default): Stops at first error
ordered: false: Skips bad docs, inserts good ones

Use Case: Importing 1 million logs, don’t let one bad line stop everything!

2. Write Concern (For Experts)

db.heroes.insertOne(
  { name: "Emergency Hero" },
  { writeConcern: { w: "majority", wtimeout: 5000 } }
)

Means: Wait until most servers confirm the write.
Use in: Banking, medical systems


๐Ÿ’ก Performance Note: insertOne vs insertMany Speed

When inserting multiple documents, insertMany is not just convenient, it’s faster. MongoDB groups many insert operations into a single network call and writes them in batches internally. This reduces round trips and improves performance.

  • insertOne: One document per network request.
  • insertMany: Many documents in one request (less latency).

Pro Tip: If you’re importing large data (logs, CSVs, or seed data), always prefer insertMany with { ordered: false } for the best throughput.


Part 6: Mini Project : Build a Full Hero Roster

Let’s make it real!

  1. Insert One Leader
    db.heroes.insertOne({
      name: "Captain Nova",
      power: "Leadership",
      level: 10,
      isLeader: true,
      team: ["Aarav", "Priya", "Sanya"]
    })
  2. Insert Many Recruits
    db.heroes.insertMany([
      { name: "Zara", power: "Lightning", level: 6, skills: ["zap", "storm"] },
      { name: "Leo", power: "Shape Shift", level: 5, skills: ["wolf", "bird"] }
    ])
  3. Check Your Academy
    db.heroes.countDocuments()
    → 8 heroes!
    
    db.heroes.find({ level: { $gte: 7 } }).pretty()
    → Shows advanced heroes
    

Part 7: Common Mistakes & Fixes

MistakeFix
Forgetting commas in array["a", "b",] → ["a", "b"]
Using insert (old command)Use insertOne or insertMany
Wrong databaseAlways use heroAcademy first
Duplicate _idLet MongoDB auto-generate or use unique

Part 8: Tips for All Levels

For Students & Beginners

  • Use Compass to avoid typos
  • Start with insertOne
  • Make a "Pet Diary" or "Game Scores"

For Medium Learners

Use validation when creating collection:

db.createCollection("heroes", {
  validator: { $jsonSchema: {
    required: ["name", "power"],
    properties: { level: { bsonType: "int", minimum: 1 } }
  }}
})

Catch errors:

try {
  db.heroes.insertMany([...])
} catch (e) {
  print("Error: " + e)
}

For Experts

db.heroes.bulkWrite([
  { insertOne: { document: { name: "X" } } },
  { updateOne: { filter: { name: "Y" }, update: { $inc: { level: 1 } } } }
])

Seed data with MongoDB Atlas Data Lake
Use change streams to react to new inserts


Part 9: Cheat Sheet (Print & Stick)

CommandWhat It Does
db.collection.insertOne({})Add 1 document
db.collection.insertMany([])Add many documents
{ ordered: false }Skip bad docs
db.collection.find().pretty()View nicely
db.collection.countDocuments()Count total

Final Words

You’re a Document Master.

You just:

  • Used insertOne → Add one hero
  • Used insertMany → Add many at once
  • Worked with shell and GUI
  • Learned pro tricks like ordered: false

Your Mission:

use myWorld
db.legends.insertOne({
  name: "You",
  power: "MongoDB Master",
  level: 100,
  message: "I can insert anything!"
})

You’re now a Certified MongoDB Inserter!


๐Ÿ”ฅ Challenge Mode: Take It Further

You’ve mastered insertOne and insertMany, now try these bonus challenges:

  1. Create a new collection called villains and insert 5 records with insertMany.
  2. Use insertOne to add a “boss villain” with a special field called archEnemies listing your heroes.
  3. Run db.villains.find().pretty() to view your villain roster.
  4. Bonus: Write a query to find all heroes with level ≥ 6 and store them in a new collection called eliteHeroes.

Goal: Build your own mini “Hero vs Villain” database!


๐Ÿš€ Take Your MongoDB Skills to the Next Level!

Loved this hero-themed tutorial? Put your skills to the test and become a Certified MongoDB Inserter

  • ๐Ÿ’ก Try creating your own collections and insert multiple documents.
  • ๐Ÿ’ก Experiment with ordered: false and bulk inserts.
  • ๐Ÿ’ก Share your hero and villain rosters in the comments below.
Start Your MongoDB Adventure →

Don’t forget to bookmark this tutorial for future reference!

Resources:

Keep filling the magic diary!

Creating Your First MongoDB Database and Collection (Step-by-Step Tutorial)



Creating Your First MongoDB Database and Collection

A Super Fun, Step-by-Step Adventure for Beginner to Expert Level


What is MongoDB?
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents instead of rigid tables used in SQL databases. This makes it perfect for modern apps, projects, and learning how data really works!

Imagine you’re opening a magic toy box where you can store toys, games, books, and secret treasures — all in one place! In MongoDB, a database is your toy box, and a collection is a shelf inside it. This tutorial teaches you how to create your first database and collection using simple words, fun examples, and real tools, perfect for students, but packed with pro tips for experienced learners.

We’ll use:

  • mongosh (the modern MongoDB shell)
  • MongoDB Compass (a click-and-play GUI)
  • Real images from MongoDB
  • A fun "Pet Shop" project

Level: Beginners to Pro


Let’s open the toy box!

Part 1: What Are Databases and Collections?

TermReal-Life ExampleMongoDB Meaning
DatabaseA big toy boxA container for all your data
CollectionA shelf inside the toy boxA group of similar items (documents)

Fun Fact: You don’t need to “create” a database first! MongoDB makes it automatically when you add data!


Part 2: Method 1- Using mongosh (The Command Way)

Step 1: Open mongosh

After installing MongoDB (see our first tutorial), open your terminal (Linux/macOS) or Command Prompt/PowerShell (Windows).

Type:

mongosh

You’ll see:

test>

Beginner Tip: The > is your magic wand. Type spells (commands) here!

Step 2: Create Your First Database – petshop

use petshop

What happens?
MongoDB switches to (or creates) a database called petshop.
But it’s invisible until you add data!
Like: Opening a new toy box labeled “Pet Shop” , but it’s empty!

Step 3: Create Your First Collection – animals

db.animals.insertOne({
  name: "Buddy",
  species: "Dog",
  age: 3,
  color: "Golden",
  loves: ["balls", "walks", "treats"]
})

Output:

{
  acknowledged: true,
  insertedId: ObjectId("671a5f2c8e4b2c1f9d5e7a3d")
}

Magic Moment!
petshop database is now created
animals collection is now created
Buddy the dog is now stored
Beginner Example: You just put the first toy (Buddy) on the “Animals” shelf!

Step 4: Add More Pets!

db.animals.insertMany([
  {
    name: "Whiskers",
    species: "Cat",
    age: 2,
    color: "Gray",
    loves: ["napping", "laser pointer"]
  },
  {
    name: "Goldie",
    species: "Fish",
    age: 1,
    color: "Orange",
    loves: ["swimming", "bubbles"]
  }
])

Pro Tip: Use insertMany() for bulk add faster and cleaner!

Step 5: See Your Data!

db.animals.find()

Output:

{ "_id": ObjectId("..."), "name": "Buddy", ... }
{ "_id": ObjectId("..."), "name": "Whiskers", ... }
{ "_id": ObjectId("..."), "name": "Goldie", ... }

Pretty View:

db.animals.find().pretty()

Beginner Win: You just opened the toy box and saw all pets!

Step 6: Check What’s Created

show dbs

→ Shows all databases (now includes petshop)

show collections

→ Shows animals

db.animals.countDocuments()

→ Returns 3 (total pets)



Part 3: Method 2 – Using MongoDB Compass (The Click Way)

Step 1: Open Compass

Download: mongodb.com/compass
Open the app.

Step 2: Connect to Your Local MongoDB

Connection: mongodb://localhost:27017
Click Connect

Step 3: Create Database & Collection Visually

Click "Create Database"
Name: petshop
Collection: animals
Click Create

Step 4: Add a Pet with Clicks!

Click on animals collection
Click "Add Data" → "Insert Document"
Paste or type:

{
  "name": "Fluffy",
  "species": "Rabbit",
  "age": 1,
  "color": "White",
  "loves": ["carrots", "hopping"]
}

Click Insert
Beginner Magic: No typing commands! Just click and add!

Step 5: See Your Pet Shop!

You’ll see all pets in a beautiful table:
Expert Feature: Click column headers to sort, or use filter bar:

{ "species": "Dog" }


Part 4: Understanding the Magic Behind the Scenes

ActionWhat MongoDB Does Automatically
use petshopSwitches context (no file created yet)
insertOne()Creates DB + Collection + Document
show dbsLists only DBs with data
No CREATE DATABASE command needed!


Part 5: Mini Project – Build a Full Pet Shop!

1. Add More Collections

// Toys collection
db.toys.insertOne({
  name: "Squeaky Ball",
  for: "Dog",
  price: 5.99,
  inStock: true
})

// Owners collection
db.owners.insertOne({
  name: "Aarav",
  phone: "9876543210",
  pets: ["Buddy", "Whiskers"]
})

2. Smart Queries

// Find dogs older than 2
db.animals.find({ species: "Dog", age: { $gt: 2 } })

// Find pets that love "treats"
db.animals.find({ loves: "treats" })

// Count cats
db.animals.countDocuments({ species: "Cat" })

3. Update a Pet

db.animals.updateOne(
  { name: "Buddy" },
  { $set: { age: 4, vaccinated: true } }
)

4. Delete a Toy (Carefully!)

db.toys.deleteOne({ name: "Squeaky Ball" })


Part 6: Pro Tips for All Levels

For students & Beginners

  • Use Compass to avoid typos
  • Make a "Game Collection" with characters
  • Always use .pretty() in mongosh

For Medium Learners

db.animals.createIndex({ species: 1 })
db.createCollection("animals", {
  validator: {
    $jsonSchema: {
      required: ["name", "species"],
      properties: {
        age: { bsonType: "int", minimum: 0 }
      }
    }
  }
})

Note: In modern versions of MongoDB, "bsonType": "int" can also be written as "bsonType": "number" depending on your environment and data type. Both work correctly as long as the field value matches the expected numeric format.


For Experts

db.createCollection("logs", { capped: true, size: 100000 })

db.animals.createIndex({ name: "text" })
db.animals.find({ $text: { $search: "Buddy" } })

// Use Atlas for cloud (no install!)
cloud.mongodb.com


Part 7: Cheat Sheet (Print & Stick!)

CommandWhat It Does
mongoshOpen shell
use dbnameSwitch/create database
db.collection.insertOne({})Add one item
db.collection.insertMany([])Add many items
db.collection.find()Show all
db.collection.find().pretty()Show nicely
show dbsList databases
show collectionsList shelves
db.collection.drop()Delete shelf
db.dropDatabase()Delete entire toy box


Part 8: Common Mistakes & Fixes

MistakeFix
Typing create database petshopNot needed! Just use petshop
Forgetting quotes in stringsUse "name": "Buddy"
Using wrong collection nameCheck with show collections
Data not showing in show dbsYou must insert data first!


๐Ÿ’ก Quick Quiz & Challenge

  1. What command automatically creates both a database and collection in MongoDB?
  2. How do you display all documents in a collection neatly?
  3. Which MongoDB GUI lets you create databases with just clicks?

Bonus Challenge:
Try adding an owners-to-pets relationship using ObjectId references. Here’s an example to get you started:

// Step 1: Insert pets
db.animals.insertOne({
  name: "Buddy",
  species: "Dog"
})

// Step 2: Get Buddy's _id
var buddyId = db.animals.findOne({ name: "Buddy" })._id

// Step 3: Create an owner referencing Buddy
db.owners.insertOne({
  name: "Aarav",
  pets: [buddyId]
})

// Step 4: Verify relationship
db.owners.aggregate([
  {
    $lookup: {
      from: "animals",
      localField: "pets",
      foreignField: "_id",
      as: "petDetails"
    }
  }
])

๐ŸŽ‰ Pro Tip: This approach helps you model real relationships between collections just like linking tables in SQL, but more flexible!



Final Words

You Did It!


You just:
  • Created your first database (petshop)
  • Made a collection (animals)
  • Added, viewed, and managed real data
  • Used both command line and GUI

Fun Learned: Infinite

Your Next Mission:

use myWorld
db.heroes.insertOne({
  name: "You",
  power: "MongoDB Master",
  level: "Expert"
})

You’re now a Certified MongoDB Creator!



๐Ÿ‘‰ Next Tutorial: Level Up Your MongoDB Skills

Now that you’ve mastered databases and collections, take your next step in learning MongoDB queries and relationships!

๐Ÿš€ Next: Master MongoDB Queries and Relationships

Coming soon: Learn how to search, filter, and connect data across collections like a pro!

Resources:

Keep building magic toy boxes! ๐Ÿงธ✨

How to Install MongoDB on Windows, Linux & macOS (Step-by-Step)

๐Ÿงฐ Installing MongoDB: A Simple Guide for Everyone

Welcome to this tutorial on installing MongoDB.

MongoDB is like a super smart digital filing cabinet that helps you store and organize large amounts of information quickly and easily. It is widely used by websites, apps, and games to manage data.

Whether you're a beginner just starting out or an expert needing a quick refresher, this guide will help you install MongoDB on Windows, Linux, or macOS.

Think of MongoDB as a box of LEGO bricks: each “brick” holds information, and you can stack them however you want. There are no strict table rules like traditional databases.


๐Ÿ“‘ Table of Contents


๐Ÿ“– What is MongoDB and Why Use It?

MongoDB is a NoSQL database, meaning it doesn’t use tables like old-school relational databases. Instead, it stores data in flexible “documents” similar to JSON files.

Benefits:

  • For beginners: Easy to learn, no complex SQL needed.
  • For experts: Scalable, supports sharding, and offers powerful querying.

๐Ÿงช System Requirements

OS Minimum Version Notes
Windows 64-bit, Windows 10+ Chocolatey or manual install
Linux Ubuntu 20.04+, CentOS 8+ APT or manual install supported
macOS 11 (Big Sur)+ Intel & Apple Silicon supported

๐Ÿ‘‰ Download MongoDB from the official website: https://www.mongodb.com


⚡ Method 1: Install Using Package Managers (Recommended)

Package managers are like app stores for your computer, handling downloads, installations, and updates automatically.

๐Ÿง Linux (Ubuntu/Debian)

  1. Update your system:
    sudo apt update
    sudo apt upgrade -y
  2. Add MongoDB GPG key & repository:
    wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
    echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
    sudo apt update
  3. Install MongoDB:
    sudo apt install -y mongodb-org
  4. Start and enable MongoDB:
    sudo systemctl start mongod
    sudo systemctl enable mongod
  5. Test the installation:
    mongosh
    > db.version()

๐Ÿ’ก Pro Tip: Use mongod --config /etc/mongod.conf for custom configs (e.g., bind IP or authentication).

๐ŸŽ macOS (Homebrew)

  1. Install Homebrew:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  2. Tap and install MongoDB:
    brew tap mongodb/brew
    brew install mongodb-community@7.0
  3. Start MongoDB as a service:
    brew services start mongodb/brew/mongodb-community
  4. Or run manually:
    mongod --config /opt/homebrew/etc/mongod.conf
  5. Test:
    mongosh

๐ŸชŸ Windows (Chocolatey)

  1. Install Chocolatey from https://chocolatey.org.
  2. Open PowerShell as Administrator and run:
    choco install mongodb
  3. MongoDB installs as a Windows service and starts automatically.
  4. Test:
    mongosh

⚠️ If Chocolatey isn’t available, use the manual installation method below.


๐Ÿงฐ Method 2: Manual Installation (For More Control)

This method is great for learning how MongoDB works under the hood or troubleshooting advanced setups.

๐ŸชŸ Windows Manual Installation

  1. Download the MSI installer from MongoDB download page.
  2. Run the installer, choose “Complete” setup, and check “Install MongoDB as a Service”.
  3. Create the data directory:
    mkdir C:\data\db
  4. Start MongoDB manually (if not installed as a service):
    "C:\Program Files\MongoDB\Server\7.0\bin\mongod.exe"
  5. (Optional) Add MongoDB to PATH:
    C:\Program Files\MongoDB\Server\7.0\bin
  6. Troubleshooting:
    • If port 27017 is busy, change port with --port 27018.
    • Advanced config: edit mongod.cfg in the install directory.

๐Ÿง Linux Manual Installation (e.g., CentOS/RHEL)

  1. Download the TGZ package for your distro.
  2. Extract and move:
    tar -xzf mongodb-linux-x86_64-7.0.tgz
    sudo mkdir -p /opt/mongodb
    sudo mv mongodb-linux-x86_64-7.0 /opt/mongodb
  3. Add to PATH:
    export PATH=$PATH:/opt/mongodb/bin
    source ~/.bashrc
  4. Create the data directory:
    sudo mkdir -p /data/db
    sudo chown $(whoami) /data/db
  5. Run MongoDB:
    mongod

๐ŸŽ macOS Manual Installation (Without Homebrew)

  1. Download TGZ for macOS (Intel or ARM).
  2. Extract and move:
    sudo mkdir -p /opt/mongodb
    sudo tar -xzf mongodb-macos-x86_64-7.0.tgz -C /opt/mongodb
  3. Symlink binaries:
    sudo ln -s /opt/mongodb/bin/* /usr/local/bin/
  4. Create data dir and run (same as Linux).
  5. For Apple Silicon: use the ARM64 build and verify with:
    file mongod

✅ Verifying Installation (All OS)

  1. Open MongoDB Shell:
    mongosh
  2. Check connection:
    db.runCommand({ connectionStatus: 1 })
  3. Check version:
    mongod --version

⚠️ If mongosh isn’t found, make sure your PATH includes the bin directory.


๐Ÿ” Post-Installation Best Practices

Enable Authentication

use admin
db.createUser({
  user: "admin",
  pwd: "strongpassword",
  roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]
})

Edit mongod.conf:

security:
  authorization: enabled

Restart MongoDB service after making changes.

Bind IP & Firewall

  • Bind IP: For remote access, set net.bindIp: 0.0.0.0 (secure with firewall).
  • Firewall:
    • Windows: Allow port 27017
    • Linux: sudo ufw allow 27017
    • macOS: System Preferences → Security → Firewall

Updates

  • Package Manager: sudo apt upgrade mongodb-org or brew upgrade
  • Manual: Download new version and backup /data/db

๐Ÿงน Uninstall or Upgrade MongoDB

If you ever need to remove or upgrade MongoDB, here are quick steps by OS:

๐Ÿง Linux (Ubuntu/Debian)

sudo systemctl stop mongod
sudo apt purge mongodb-org*
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

๐ŸŽ macOS (Homebrew)

brew services stop mongodb/brew/mongodb-community
brew uninstall mongodb/brew/mongodb-community
rm -rf /usr/local/var/mongodb

๐ŸชŸ Windows

  1. Stop the MongoDB service from Services.msc or with:
    net stop MongoDB
  2. Uninstall from Control Panel or:
    choco uninstall mongodb
  3. Delete C:\data\db if you want to remove stored databases.

To upgrade, simply download the new version and follow the same installation method. Always backup your data directory before upgrading.


๐Ÿš€ Performance Tips for Experts

  • Use WiredTiger storage engine (default).
  • Store storage.dbPath on SSD.
  • Monitor performance with:
    mongostat
    or use MongoDB Compass GUI.

๐Ÿง  Tools and Next Steps

  • MongoDB Compass: GUI tool to visualize databases.
  • Drivers: Install via pip (Python), npm (Node.js), etc.
  • Backup: Use mongodump for safe exports.


๐Ÿ”— Official Documentation & References


๐Ÿ‘‰ Beginner project:

use mydb
db.users.insertOne({ name: "Alice", age: 10 })

๐Ÿงญ Practice on a virtual machine first.
For issues, check logs in:

  • /var/log/mongodb (Linux)
  • Install dir (Windows/macOS)

❓ Frequently Asked Questions (FAQ)

1. How do I check if MongoDB is installed correctly?

Open your terminal or command prompt and run:

mongosh

If the shell opens, run:

db.runCommand({ connectionStatus: 1 })

You should see "ok" : 1 in the output.

2. Where is MongoDB installed on my system?

  • Windows: C:\Program Files\MongoDB\Server\7.0\bin
  • Linux: /usr/bin or /opt/mongodb/bin
  • macOS: /usr/local/bin or Homebrew directory

3. What port does MongoDB use?

MongoDB uses port 27017 by default. You can change it in mongod.conf using:

net:
  port: 27018

4. How do I uninstall MongoDB?

Follow the uninstall steps in the Uninstall / Upgrade section of this article for your OS.

5. How do I secure my MongoDB installation?

  • Enable authentication and create an admin user.
  • Use net.bindIp: 127.0.0.1 or firewall rules to limit access.
  • Keep your MongoDB version up to date.

6. Can I run MongoDB on a virtual machine?

Yes. MongoDB runs well on virtual machines or containers like Docker. This is a great way to practice without affecting your main system.

Feel free to ask in comment if you have any question or suggestions.๐ŸŽ‰ Happy coding!

Normalization vs Denormalization: SQL vs MongoDB Practice task Solution

Solution: Normalization vs Denormalization Practice


This tutorial provides the complete solution to the earlier practice task comparing normalization in SQL and denormalization in MongoDB. If you haven't attempted the exercise, click here to try it first.

Here's the full solution to the Normalization vs Denormalization practice exercise using both SQL (normalized) and MongoDB (denormalized) approaches.


๐Ÿ”น Task A: Normalized Design (SQL Style)


1. Table Structure

Authors Table

CREATE TABLE Authors (
  AuthorID INT PRIMARY KEY,
  AuthorName VARCHAR(100),
  Email VARCHAR(100)
);

Books Table

CREATE TABLE Books (
  BookID INT PRIMARY KEY,
  Title VARCHAR(150),
  AuthorID INT,
  FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID)
);


2. Sample Data Insertion

INSERT INTO Authors (AuthorID, AuthorName, Email) VALUES
(1, 'Jane Austen', 'jane.austen@example.com'),
(2, 'Mark Twain', 'mark.twain@example.com');

INSERT INTO Books (BookID, Title, AuthorID) VALUES
(101, 'Pride and Prejudice', 1),
(102, 'Emma', 1),
(103, 'Adventures of Tom Sawyer', 2);


3. SQL Query to Join Data

SELECT Books.Title, Authors.AuthorName
FROM Books
JOIN Authors ON Books.AuthorID = Authors.AuthorID;

๐Ÿ” Expected Output:


+----------------------------+-------------+
| Title                      | AuthorName  |
+----------------------------+-------------+
| Pride and Prejudice        | Jane Austen |
| Emma                       | Jane Austen |
| Adventures of Tom Sawyer   | Mark Twain  |
+----------------------------+-------------+


๐Ÿ”น Task B: Denormalized Design (MongoDB Style)


1. Book Documents with Embedded Author Info

db.books.insertMany([
  {
    book_id: 101,
    title: "Pride and Prejudice",
    author: {
      author_id: 1,
      name: "Jane Austen",
      email: "jane.austen@example.com"
    }
  },
  {
    book_id: 102,
    title: "Emma",
    author: {
      author_id: 1,
      name: "Jane Austen",
      email: "jane.austen@example.com"
    }
  },
  {
    book_id: 103,
    title: "Adventures of Tom Sawyer",
    author: {
      author_id: 2,
      name: "Mark Twain",
      email: "mark.twain@example.com"
    }
  }
]);


2. MongoDB Query to Find Books by Author Name

db.books.find({ "author.name": "Jane Austen" }, { title: 1, _id: 0 });

๐Ÿ” Expected Output:


[
  { title: "Pride and Prejudice" },
  { title: "Emma" }
]

๐Ÿ”ธ Bonus Challenge: Updating Author Email


๐Ÿง  In Normalized (SQL):

  • You update once in the Authors table:

UPDATE Authors
SET Email = 'new.jane.austen@example.com'
WHERE AuthorID = 1;

Change is reflected across all books automatically (since books reference the author ID).


๐Ÿง  In Denormalized (MongoDB):

  • You must update all documents containing the embedded author data:

db.books.updateMany(
  { "author.author_id": 1 },
  { $set: { "author.email": "new.jane.austen@example.com" } }
);

❗ Requires multiple updates — more effort, but often better read performance.

๐Ÿ”— Want a deeper look at MongoDB's schema design strategies? Check out our MongoDB Schema Design Guide.


✅ Summary: What You’ve Learned


Concept SQL MongoDB (NoSQL)
Data Structure Normalized into separate tables Denormalized with embedded docs
Redundancy Low High
Update Effort One update in Authors table Multiple document updates
Read Simplicity Needs JOIN Direct query, no joins needed

๐Ÿ That’s it! You now understand the core differences between normalized and denormalized database design using SQL and MongoDB. Got questions or want more practice? Let us know in the comments or check out more tutorials in our Learning Series.


Featured Post

Master MongoDB with Node.js Using Mongoose: Complete Guide

Working with MongoDB from Node.js using Mongoose Your Magical Mongoose Pet That Makes MongoDB Super Easy For Beginner to Expert Level ...

Popular Posts