Showing posts with label MongoDB Tutorial. Show all posts
Showing posts with label MongoDB Tutorial. Show all posts

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

๐Ÿ“š Table of Contents


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! ๐Ÿงธ✨

MongoDB Data Types & BSON Explained : Easy Guide from Beginner to Expert


MongoDB Data Types & BSON Format

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


Imagine you are packing a magic backpack for a trip. You can put in toys, books, photos, numbers, maps, and even secret codes — all in one bag! MongoDB does the same with your data using BSON (Binary JSON). This tutorial explains MongoDB data types and BSON format in the simplest way but with deep insights for pros too. We’ll use:

  • Fun examples (like a student diary)
  • Real images (from MongoDB docs)
  • Beginner → Expert tips

Let’s open the magic backpack!



Part 1: What is BSON?

JSON vs BSON : The Magic Difference

JSON (Human-Readable) vs BSON (MongoDB’s Secret Code)

  • Text like a letter → JSON
  • Binary like a robot language → BSON
  • Slow to send → JSON
  • Super fast → BSON
  • No dates, no big numbers → JSON
  • Full support for all types → BSON
Here is the difference in tabular format:
JSON (Human-Readable) BSON (MongoDB’s Secret Code)
Text like a letter
Slow to send
No dates, no big numbers
Binary like a robot language
Super fast
Full support for all types

Think of it like this:
JSON = Writing a postcard
BSON = Sending a high-speed encrypted video

MongoDB converts your data into BSON behind the scenes so it can store and fetch it super fast.

Why BSON is Awesome (For Experts)

  • Binary → 10x faster than JSON
  • Supports 32 data types (vs JSON’s 6)
  • Stores metadata like field order
  • Enables rich queries (e.g., find all dates in 2025)


Part 2: MongoDB Data Types – The Magic Items in Your Backpack

Let’s meet the 12 most important data types with real-life examples!

1. String – Words, Names, Messages

{
  "name": "Priya",
  "message": "I love coding!"
}

Like: Writing your name on a notebook
Use: Names, emails, comments

๐Ÿ’ก Expert Tip: UTF-8 supported. Max 16MB per document.

2. Integer – Whole Numbers (32-bit & 64-bit)

{
  "age": 13,
  "score": 95
}

Like: Counting marbles

  • Int32 → -2.1 billion to 2.1 billion
  • Int64 → Much bigger (use for IDs, counters)
db.students.insertOne({ age: NumberInt(13) })     // 32-bit
db.students.insertOne({ age: NumberLong(9007199254740992) }) // 64-bit

3. Double – Decimal Numbers

{
  "height": 5.5,
  "temperature": 36.6
}

Like: Measuring height in feet
Use: Prices, ratings, GPS

{ "price": 19.99 }

4. Boolean – True or False

{
  "isStudent": true,
  "hasSubmitted": false
}

Like: Light switch: ON or OFF
Use: Flags, settings

5. Date – Time & Date

{ "birthday": ISODate("2012-05-15T00:00:00Z") }

Like: Marking your birthday on a calendar

db.events.insertOne({
  name: "Sports Day",
  date: new Date()  // Current time
})
Expert Insight: Stored as 64-bit integer (milliseconds since 1970). Perfect for sorting!

6. ObjectId – Unique ID (Auto-Generated)

{ "_id": ObjectId("671a3f1d8e4b2c1f9d5e7a2c") }

Like: A special sticker with a unique code on every toy

Structure (12 bytes):

  • Timestamp (4)
  • Machine ID (3)
  • Process ID (2)
  • Counter (3)

Why it’s cool: Globally unique, Time-ordered, No central ID server needed

7. Array – Lists of Anything!

{
  "hobbies": ["cricket", "drawing", "coding"],
  "scores": [95, 88, 100]
}

Like: A lunchbox with multiple snacks

db.students.find({ hobbies: "cricket" })
Expert: Use $all, $size, $elemMatch for advanced array queries.

8. Embedded Document – Data Inside Data

{
  "name": "Amit",
  "address": {
    "street": "MG Road",
    "city": "Delhi",
    "pin": 110001
  }
}

Like: A folder inside a folder

db.students.find({ "address.city": "Delhi" })
Pro Tip: Embedding = Fast reads. Normalize = Less duplication.

Real-World Example:

Using embedded documents is perfect for e-commerce orders:


{
  "orderId": 12345,
  "customer": {
    "name": "Priya",
    "email": "priya@example.com"
  },
  "items": [
    {"product": "Book", "qty": 2},
    {"product": "Pen", "qty": 5}
  ]
}

9. Null – Empty or Missing

{ "middleName": null }

Like: A blank space in a form

10. Binary Data – Photos, Files, Secrets

db.files.insertOne({
  name: "photo.jpg",
  data: BinData(0, "base64string...")
})

Like: Storing a real photo in your diary
Use Case: Thumbnails, encrypted data

11. Regular Expression – Pattern Search

db.users.find({ name: /^A/ })  // Names starting with A
db.users.find({ name: /kumar$/i })  // Ends with "kumar", case-insensitive

Like: Searching with wildcards

12. JavaScript Code – Store Functions (Rare!)

{ "func": { "$code": "function() { return 'Hi'; }" } }
⚠️ Warning: Not for production. Use with caution.


Part 3: BSON in Action – See the Magic!

Let’s insert a student and see how MongoDB stores it:

use school
db.students.insertOne({
  name: "Rohan",
  age: 13,
  height: 5.4,
  isActive: true,
  birthday: ISODate("2012-03-10"),
  hobbies: ["cricket", "music"],
  address: {
    city: "Mumbai",
    pin: 400001
  }
})

Behind the Scenes (BSON View)

MongoDB converts this to binary BSON:

\x16\x00\x00\x00           // Document length
  \x02 name: \x00 ...     // String
  \x10 age: \x0D\x00...   // 32-bit int
  \x01 height: ...        // Double
  \x08 isActive: \x01     // Boolean
  \x09 birthday: ...      // Date
  \x04 hobbies: ...       // Array
  \x03 address: ...       // Sub-document
\x00                       // End



Part 4: Data Type Cheat Sheet (Print & Stick!)

Type Example mongosh Syntax
String "Rohan" "Rohan"
Integer (32) 13 NumberInt(13)
Integer (64) 9007199254740992 NumberLong("...")
Double 5.5 5.5
Boolean true true
Date 2025-10-30 ISODate("2025-10-30")
ObjectId Auto-generated ObjectId()
Array ["a", "b"] ["a", "b"]
Embedded Doc { city: "Delhi" } { city: "Delhi" }
Null null null


Part 5: Common Mistakes & Fixes


Mistake Fix
Using 13 as string "13" Use numbers for math: age: 13
Storing dates as strings Use ISODate() for proper sorting
Forgetting NumberLong() for big nums Use NumberLong(1234567890123)
Arrays with mixed types Avoid! Keep types consistent


Part 6: Mini Project – Build a "Student Card"

db.cards.insertOne({
  _id: ObjectId(),
  name: "Sanya",
  rollNo: NumberInt(25),
  grade: 8.5,
  isPrefect: true,
  joinDate: ISODate("2024-04-01T00:00:00Z"),
  subjects: ["Math", "Science", "English"],
  marks: {
    math: 92,
    science: 88,
    english: 90
  },
  photo: BinData(0, "base64string..."),  // Optional
  notes: null
})

Now Query It!

// Find 8th graders with >90 in Math
db.cards.find({
  "marks.math": { $gt: 90 }
})

// Update grade
db.cards.updateOne(
  { name: "Sanya" },
  { $set: { grade: 8.7 } }
)

Try in Compass! See it as a beautiful card.


Try It Yourself:

Insert a new student with your own hobbies and query only students who like "music".


// Hint:
db.students.find({ hobbies: "music" })


Part 7: Tips for All Levels

For Beginners

  • Use Compass GUI to see types visually
  • Practice with insertOne() and find()
  • Make a "Game Inventory" with arrays

For Medium Learners

Use schema validation to enforce types:

db.createCollection("students", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "age"],
      properties: {
        name: { bsonType: "string" },
        age: { bsonType: "int" }
      }
    }
  }
})

For Experts

  • Use BSON type checking in drivers
  • Optimize with partial indexes on specific types
  • Use Decimal128 for money:
    { price: NumberDecimal("19.99") }

Final Words

You now know:

  • BSON = MongoDB’s super-fast binary format
  • 12+ data types = From strings to photos
  • How to store, query, and master data like a pro!

Fun Learned: Infinite



Your Mission:

use myBackpack
db.items.insertOne({
  name: "Magic Wand",
  power: 9000,
  isLegendary: true,
  discovered: new Date()
})

You’re now a MongoDB Data Wizard!


Frequently Asked Questions (FAQ)

1. What is BSON in MongoDB?

BSON (Binary JSON) is MongoDB’s binary format for storing data. It extends JSON by supporting additional data types like Date, ObjectId, and Binary, making storage and querying faster and more flexible.

2. Why does MongoDB use BSON instead of JSON?

MongoDB uses BSON because it’s faster and more efficient than JSON. It supports rich data types, preserves field order, and allows quick encoding/decoding for large-scale operations.

3. What are the most common MongoDB data types?

The most commonly used MongoDB data types include String, Integer, Double, Boolean, Date, ObjectId, Array, and Embedded Documents.

4. What is the difference between Int32, Int64, and Double in MongoDB?

Int32 and Int64 store whole numbers with 32-bit and 64-bit precision respectively. Double stores floating-point numbers (decimals) using IEEE-754 format. Use Int32 for small counters, Int64 for large IDs, and Double for measurements or prices.

5. How can I view BSON data in human-readable format?

MongoDB automatically converts BSON to JSON when displaying data in tools like mongosh or Compass. You can also use tojson() in the shell to see readable JSON output.

6. What is ObjectId and how is it generated?

ObjectId is a 12-byte unique identifier generated automatically by MongoDB. It includes a timestamp, machine ID, process ID, and a counter — ensuring global uniqueness and time ordering.

7. When should I use Embedded Documents vs References?

Use Embedded Documents when data is frequently read together (e.g., user profile with address). Use References when data is large or shared across documents (e.g., users referencing a separate roles collection).

8. What is Decimal128 and when should I use it?

Decimal128 is a high-precision numeric type used for financial or scientific data. Use it for currency, measurements, or when precision beyond Double is required.

9. What are common mistakes beginners make with MongoDB data types?

  • Storing numbers as strings (e.g., "13" instead of 13).
  • Using string dates instead of ISODate().
  • Mixing data types in arrays.
  • Ignoring NumberLong() for large integers.

10. How can I practice MongoDB data types easily?

Use the MongoDB Atlas free tier or Compass GUI to create collections, insert sample documents, and explore BSON structure visually.


Resources:

Keep packing your magic backpack!

๐Ÿ’ก Have questions? Drop a comment below!

Basic MongoDB Commands Tutorial: Learn mongo, mongosh, and GUI Tools Step-by-Step


Basic MongoDB Commands: mongo, mongosh, and GUI Tools

A Super Simple, Fun, and Powerful Guide for Everyone


Imagine MongoDB as a magic notebook where you can write anything—stories, drawings, lists, or even secret codes. You don’t need to follow strict rules like in a school register. This MongoDB commands tutorial teaches you how to talk to MongoDB using simple commands and cool tools.Whether you're just starting or a pro developer, this guide is made for you!

We’ll cover:

  • mongo (old shell still used sometimes)
  • mongosh (new, modern shell, the future!)
  • GUI Tools (like clicking buttons instead of typing!)

Let’s begin!


Part 1: What Are These Tools?

ToolWhat It IsBest For
mongoOld command-line shellLegacy systems, quick checks
mongoshNew and improved shell (2021+)Everyone! Modern, colorful, smart
GUI ToolsClick-and-play apps (like Compass)Beginners, visual learners, fast testing

Fun Fact: mongosh = MongoDB Shell. It’s like upgrading from a bicycle to a rocket bike!


Part 2: Starting with mongosh (The Best Way!)


Step 1: Open mongosh

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

Type:

mongosh

You’ll see something like this:

Current Mongosh Log ID:  671a1f2c...
Connecting to:           mongodb://127.0.0.1:27017/?directConnection=true
Using MongoDB:           7.0.5
Using Mongosh:           2.2.12

test>

Beginner Tip: The > is your cursor. Type commands here and press Enter!

Basic Commands You Must Know

Let’s learn with a school example! We’ll store student info.

1. Switch to a Database

use school

Creates or switches to school database. Like opening a new notebook labeled "School".

Pro Tip: Even if it doesn’t exist, MongoDB creates it when you save data!

2. Insert a Student (Add Data)

db.students.insertOne({
  name: "Rohan",
  age: 13,
  class: "8th",
  hobbies: ["cricket", "drawing"]
})

Output:

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

Beginner Example: You just added a new student card to your magic notebook!
Expert Insight: insertOne() is atomic. Safe for one record. Use insertMany() for bulk.

3. Find Students (Search)

db.students.find()

Output:

{
  "_id": ObjectId("671a2f1d..."),
  "name": "Rohan",
  "age": 13,
  "class": "8th",
  "hobbies": ["cricket", "drawing"]
}

Pretty Print (Easier to Read):

db.students.find().pretty()

4. Find Specific Students

db.students.find({ age: 13 })
db.students.find({ "hobbies": "cricket" })

Beginner Example: Like asking, “Show me all kids who play cricket.”

Expert Tip: Use operators:
$gt → greater than
$in → in a list
$ne → not equal

db.students.find({ age: { $gt: 12 } })

5. Update a Student

db.students.updateOne(
  { name: "Rohan" },
  { $set: { class: "9th", age: 14 } }
)

Beginner Example: Rohan got promoted! We updated his class.
Expert: Use $inc to increase numbers:

db.students.updateOne(
  { name: "Rohan" },
  { $inc: { age: 1 } }
)

6. Delete a Student

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

Careful! This removes the student forever.
Safer Way (for testing):

db.students.deleteMany({ class: "temp" })

7. List All Databases

show dbs

8. List Collections (Tables)

show collections

9. Drop (Delete) a Collection

db.students.drop()

10. Drop Entire Database

db.dropDatabase()

Warning: Only do this if you’re sure!


Part 3: mongo vs mongosh: What’s the Difference?

Featuremongo (Old)mongosh (New)
Release Year20112021
Syntax HighlightingNoYes (colorful!)
Auto-completeBasicSmart (Tab = magic!)
JavaScript SupportLimitedFull ES6+
Multi-line EditingHardEasy (like code editor)
Built-in Helphelp? or .help
Future-ProofDeprecatedOfficially Supported

Bottom Line: Always use mongosh!
mongo is like an old phone. It works, but why not use a smartphone?


Part 4: GUI Tools: Click Instead of Type!


1. MongoDB Compass (Free & Official)

Download: mongodb.com/compass

How to Use (Step-by-Step)

  1. Open Compass
  2. Connect to Localhost
  3. Connection String: mongodb://localhost:27017
  4. Click Connect

See Your Data Visually!
Click on school → students
You’ll see Rohan’s data in a table!
Click to Edit, Delete, or Add
No typing needed!

Beginner Win: Perfect for learning without fear of typos.
Expert Win: Export/import JSON, analyze indexes, build aggregation pipelines visually.

2. VS Code + MongoDB Extension

For Coders Who Love VS Code

  1. Install MongoDB for VS Code extension
  2. Connect to mongodb://localhost:27017
  3. Write queries in .mongodb files with syntax highlighting
// students.mongodb
use school
db.students.find({ age: { $gte: 13 } })

Run with: Ctrl + Alt + Enter
Pro Tip: Save queries, share with team, version control with Git!

3. MongoDB Atlas (Cloud) + Web Shell

No installation needed!
Go to cloud.mongodb.com
Create free cluster
Click "Open MongoSH" → Web-based mongosh

Beginner: Try MongoDB in your browser!
Expert: Deploy, scale, monitor from one dashboard.


Part 5: Mini Project: Build a "Class Diary"

Let’s practice everything!

Step 1: Create Diary

use classDiary

Step 2: Add Entries

db.entries.insertMany([
  {
    date: "2025-10-24",
    title: "Science Fair",
    mood: "excited",
    highlights: ["Won 1st prize!", "Robot worked!"]
  },
  {
    date: "2025-10-23",
    title: "Rainy Day",
    mood: "calm",
    highlights: ["Read Harry Potter", "Ate Maggi"]
  }
])

Step 3: Query Fun

// Find happy days
db.entries.find({ mood: "excited" })

// Find entries with "prize"
db.entries.find({ highlights: "Won 1st prize!" })

// Update mood
db.entries.updateOne(
  { title: "Rainy Day" },
  { $set: { mood: "cozy" } }
)

Try in Compass too! See the data as a table.


Part 6: Cheat Sheet (Print & Stick!)

CommandWhat It Does
mongoshOpen modern shell
use dbnameSwitch/create database
db.collection.insertOne({})Add one record
db.collection.find()Show all data
db.collection.find({key: value})Search
db.collection.updateOne(filter, update)Change data
db.collection.deleteOne({})Remove one record
show dbsList databases
show collectionsList tables
db.dropDatabase()Delete current DB

Part 7: Tips for All Levels


For Beginners

  • Start with Compass – no typing!
  • Use pretty() to read output easily
  • Make a "Game Scores" or "Pet Diary" project

For Medium Learners

Practice aggregation:

db.students.aggregate([
  { $match: { age: { $gte: 13 } } },
  { $group: { _id: "$class", count: { $sum: 1 } } }
])

Learn indexing:

db.students.createIndex({ name: 1 })

For Experts

Use transactions (MongoDB 4.0+):

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

Monitor with mongostat, mongotop
Connect via drivers (Python, Node.js)

Final Words

You now know how to talk to MongoDB like a pro!
Use mongosh for power and fun
Use Compass for visual magic
Build projects to remember forever

Your Next Step:

use myWorld
db.me.insertOne({ name: "You", skill: "MongoDB Hero", level: "Beginner → Expert" })

You did it!

Resources:

Keep exploring! The world of data is waiting for you.

๐Ÿ’ก Have questions or want me to cover MongoDB queries or Atlas setup next? Drop a comment below!

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!

Practice Task: Database Security Basics

Here’s a practice task and a short quiz on Database Security Basics to reinforce Part 11’s concepts.

๐Ÿ“š This is based on Part 11: Database Security Basics. If you haven’t read it yet, check that out first.


๐Ÿงช Practice Task: Setting Up User Roles and Permissions


๐ŸŽฏ Objective:

Create users with specific roles and test their access permissions in both SQL and MongoDB.


๐Ÿ”น Part A: SQL Practice

  1. Create two users:

  • reader_user with permission to only read data from a database named SchoolDB.

  • editor_user with permission to read and write data on the same database.

  1. Test the permissions by running SELECT queries as both users, and attempt to insert data as reader_user (which should fail).


๐Ÿ”น Part B: MongoDB Practice

  1. Create two users in the library database:

  • readUser with read-only access.

  • writeUser with read and write access.

  1. Using the Mongo shell or your MongoDB client, test that:

  • readUser can query data but cannot insert or update.

  • writeUser can both query and modify data.


Quiz: Quick Security Check

  1. What SQL command is used to grant specific privileges to a user?

    a) CREATE USER
    b) GRANT
    c) REVOKE
    d) ALTER USER

  2. In MongoDB, which role allows both reading and writing to a database?

    a) read
    b) readWrite
    c) dbAdmin
    d) clusterAdmin

  3. What is the main purpose of encryption in databases?

    a) Speed up queries
    b) Protect data confidentiality
    c) Organize data in tables
    d) Backup data automatically

  4. Which security principle suggests giving users only the permissions they need?

    a) Principle of least privilege
    b) Separation of duties
    c) Data masking
    d) Role hierarchies


Next: answer key and explanations for this quiz


Full Practical Solution | SQL JOINs vs MongoDB Referencing

 Here’s the full solution to the Practice Assignment on SQL JOINs vs MongoDB Referencing, including expected outputs and explanations.


Solution: SQL JOINs vs MongoDB Referencing


๐Ÿ”น Part A: SQL Solution


1. Tables Created

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

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

2. Sample Data Inserted

INSERT INTO Authors (AuthorID, Name) VALUES
(1, 'George Orwell'),
(2, 'J.K. Rowling');

INSERT INTO Books (BookID, Title, AuthorID) VALUES
(101, '1984', 1),
(102, 'Animal Farm', 1),
(103, 'Harry Potter', 2);

3. Query Using JOIN

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

๐Ÿ“ค Expected Output:

Title Name
1984 George Orwell
Animal Farm George Orwell
Harry Potter J.K. Rowling

๐Ÿ” This result shows book titles along with the author's name using a JOIN between Books and Authors.


๐Ÿ”น Part B: MongoDB Solution

Note: MongoDB doesn’t support traditional SQL-style JOINs. Instead, you can simulate them using referencing (multiple queries) or the $lookup operator in aggregation pipelines.

1. Insert Documents

Authors Collection:

db.authors.insertMany([
  { _id: 1, name: "George Orwell" },
  { _id: 2, name: "J.K. Rowling" }
]);

Books Collection:

db.books.insertMany([
  { title: "1984", author_id: 1 },
  { title: "Animal Farm", author_id: 1 },
  { title: "Harry Potter", author_id: 2 }
]);

2. Simulating a JOIN

Step 1: Find Author Document

const author = db.authors.findOne({ name: "George Orwell" });

๐Ÿ” Expected Output:

{
  "_id": 1,
  "name": "George Orwell"
}

Step 2: Find Books by Author ID

db.books.find({ author_id: author._id });

๐Ÿ” Expected Output:

[
  { "title": "1984", "author_id": 1 },
  { "title": "Animal Farm", "author_id": 1 }
]

๐Ÿ“ To match SQL output, you'd display:

Title Author Name
1984 George Orwell
Animal Farm George Orwell

๐Ÿ”ธ Optional: Embedded Model Query

If books were stored like this:

db.books.insertOne({
  title: "1984",
  author: {
    id: 1,
    name: "George Orwell"
  }
});

Then your query:

db.books.find({ "author.name": "George Orwell" });

๐Ÿ” Would return documents with both book title and embedded author name directly, simulating a denormalized JOIN.


✅ Summary

Concept SQL (JOIN) MongoDB (Referencing)
How data is linked Foreign key + JOIN Manual field referencing (or embedding)
Queries One SQL JOIN query Two MongoDB queries (or use $lookup)
Output Title + Author from joined tables Title + Author via multiple reads or embed
Query Complexity Moderate (JOIN syntax) Simple (but more steps)

Note: MongoDB’s $lookup can perform JOIN-like operations in a single aggregation query, but it's more complex and typically used for reporting or complex analytics.


  • Move to Part 10: Transactions and Consistency

Practice Exercise on SQL Normalization vs NoSQL Denormalization (With Sample Data)

 

๐Ÿงช Practice Exercise: Normalization vs Denormalization


๐ŸŽฏ Objective:

Understand how to design data using normalization (SQL-style) and denormalization (NoSQL-style).


๐Ÿ”น Scenario:

You are managing a simple Library Database with Books and Authors.


๐Ÿ“Œ Task A: Normalize the Data (SQL style)

  1. Create tables for Books and Authors.

  2. Each book should store a reference (AuthorID) to the author.

  3. Insert sample data for 2 authors and 3 books (some books by the same author).

  4. Write an SQL query to fetch each book’s title with its author’s name.


๐Ÿ“Œ Task B: Denormalize the Data (NoSQL style)

  1. Create a MongoDB collection called books.

  2. Store author details embedded inside each book document.

  3. Insert the same sample data for 2 authors and 3 books as above.

  4. Write a MongoDB query to find all books by a specific author’s name.


๐Ÿ”น Bonus Challenge

  • Consider the scenario when an author’s information (e.g., email) changes.

  • Explain briefly how this update would differ in normalized vs denormalized models.


๐Ÿ“ Sample Data to Use


AuthorID AuthorName Email
1 Jane Austen jane.austen@example.com
2 Mark Twain mark.twain@example.com

BookID Title AuthorID
101 Pride and Prejudice 1
102 Emma 1
103 Adventures of Tom Sawyer 2


๐Ÿ’ก Hint: Use a JOIN to connect books and authors in SQL.



✍️ Tried the exercise? Share your SQL or MongoDB approach in the comments below.


Next: solution for this exercise 


NoSQL Databases Explained: Beginner's Guide to Flexible Data Storage (With Examples)


๐Ÿ”ท Part 5: Introduction to NoSQL Databases – A Flexible Alternative to Relational Models


๐Ÿ“ Introduction

So far, we’ve learned how relational databases work with structured tables, rows, and columns. But what if your data doesn’t fit neatly into tables?

Welcome to NoSQL — a more flexible way to store and manage data. Whether you're building apps with real-time feeds, handling massive data from sensors, or creating dynamic content, NoSQL databases offer a powerful solution.


๐Ÿ”น What is NoSQL?

NoSQL stands for “Not Only SQL.”
It refers to a group of databases that store and retrieve data in ways other than traditional tabular formats (used by relational databases).

NoSQL is often used for:

  • Unstructured or semi-structured data

  • High-speed, high-volume applications

  • Scalable systems like social networks, IoT platforms, or real-time analytics


๐Ÿงฐ Types of NoSQL Databases

  1. Document-Based – Stores data as JSON-like documents (e.g., MongoDB)

  2. Key-Value Stores – Stores data as simple key-value pairs (e.g., Redis)

  3. Column-Family Stores – Similar to tables but with flexible columns (e.g., Cassandra)

  4. Graph Databases – Designed to represent complex relationships (e.g., Neo4j)


๐Ÿ” Document-Based NoSQL Example (MongoDB)

Here’s how a student record might look in a NoSQL document store:

{
  "student_id": 1,
  "name": "Aisha",
  "class": "10A",
  "marks": [
    { "subject": "Math", "score": 85 },
    { "subject": "English", "score": 88 }
  ]
}

๐Ÿ”„ Compare this to the relational model where marks are in a separate table. In NoSQL, all related data can be stored together in one document.


๐Ÿ†š NoSQL vs SQL – Key Differences

Feature SQL (Relational) NoSQL (Non-Relational)
Structure Fixed tables and schemas Flexible, schema-less
Data Format Rows and columns JSON, key-value, graphs, etc.
Relationships Supports JOINs Embeds or references data
Scalability Vertical (scale-up) Horizontal (scale-out)
Best For Structured, consistent data Dynamic, varied, big data

๐Ÿ“š Real-Life Analogy

Imagine SQL is like organizing books in a library, where every book must follow a strict format (title, author, ISBN).

NoSQL is like a digital folder, where each file (document) can have different details — one may have a title and summary, another may have a title, author, and image — and that’s perfectly okay.


๐Ÿง  When to Use NoSQL?

Use NoSQL when:

  • Data structure is not fixed

  • You're dealing with lots of rapidly changing data

  • You need fast performance and easy scalability

  • Relationships between data are simple or embedded


๐Ÿง  Recap

  • NoSQL databases offer flexibility and speed for non-tabular data

  • They store data in formats like documents or key-value pairs

  • Great for modern apps, real-time systems, and unstructured data

  • Popular tools: MongoDB, Redis, Cassandra, Firebase


✅ What’s Next?

In Part 6, we’ll perform real-world CRUD operations in both SQL and NoSQL — showing how to Create, Read, Update, and Delete data with easy examples.


Practice Set: MongoDB Document Modeling Practice


Featured Post

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? ...

Popular Posts