Showing posts with label Learn MongoDB. Show all posts
Showing posts with label Learn MongoDB. 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! ๐Ÿงธ✨

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!

SQL Joins vs NoSQL Referencing: Understanding Data Relationships Easily

๐Ÿ”ท Part 9: Relationships in SQL vs Referencing in NoSQL


This is a key concept that helps readers understand how to link data across tables (SQL) or documents (NoSQL), which is essential for real-world applications like e-commerce, school systems, or social networks.


๐Ÿ“ Introduction

Most databases store related data: customers and orders, students and classes, or products and reviews.

  • In SQL, we use foreign keys and JOINs to link tables.

  • In NoSQL (like MongoDB), we use manual referencing or embedding to connect documents.

Understanding these relationship methods is essential for building scalable and maintainable database designs.


๐Ÿ”ธ 1. Relationships in SQL (Using Joins)

SQL supports:

  • One-to-One

  • One-to-Many

  • Many-to-Many
    …through foreign keys and JOINs.


✅ Example: Students and Classes (One-to-Many)


๐Ÿ“ Tables:

CREATE TABLE Students (
  StudentID INT PRIMARY KEY,
  Name VARCHAR(100)
);

CREATE TABLE Classes (
  ClassID INT PRIMARY KEY,
  StudentID INT,
  Subject VARCHAR(50),
  FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);

๐Ÿ” Fetching Related Data:

SELECT Students.Name, Classes.Subject
FROM Students
JOIN Classes ON Students.StudentID = Classes.StudentID;

➡️ This JOIN connects each student to their class records.


๐Ÿ”น 2. Relationships in MongoDB (Referencing)

In NoSQL, there are two ways to handle related data:

✅ A. Manual Referencing (Normalized approach)

// students collection
{
  _id: ObjectId("stu101"),
  name: "Aisha Khan"
}

// classes collection
{
  student_id: ObjectId("stu101"),
  subject: "Math"
}

To retrieve, you need two queries:

const student = db.students.findOne({ name: "Aisha Khan" });
const classes = db.classes.find({ student_id: student._id });

✅ B. Embedding (Denormalized approach)

{
  name: "Aisha Khan",
  classes: [
    { subject: "Math" },
    { subject: "Science" }
  ]
}

➡️ This is faster for reads, but harder to update if the same class is shared across students.


๐Ÿ”„ Comparison Table: SQL Joins vs NoSQL Referencing


Feature SQL (Joins) MongoDB (Referencing/Embedding)
Relationship type Foreign keys & JOINs Manual references or embedded documents
Querying Single JOIN query Multiple queries or nested documents
Read performance May be slower due to joins Fast if embedded
Update complexity Centralized & simple More complex with embedded structures
Data duplication Minimal Possible with embedding

๐Ÿง  Best Practices


✅ Use SQL when:

  • Data relationships are complex and frequently queried together

  • You want strong referential integrity

✅ Use NoSQL referencing when:

  • You need flexibility or horizontal scaling

  • Data isn’t always accessed together


๐Ÿ“Œ Quick Summary

  • SQL uses foreign keys and JOINs for linking tables.
  • NoSQL uses manual referencing or embedding to relate documents.
  • Joins are powerful but may affect performance in large datasets.
  • Embedding is fast but risks data duplication and update complexity.


✅ What’s Next?

In Part 10, we’ll dive into Transactions and Consistency — how SQL ensures ACID compliance, and how NoSQL handles consistency across distributed systems.


    Click Next for:
  •  practice assignment comparing SQL JOINs and MongoDB referencing

Indexing in SQL and NoSQL: Improve Database Performance with Simple Tips

 

๐Ÿ”ท Part 8: Indexing and Query Optimization in SQL and NoSQL


This post will introduce the basics of indexing in both SQL and MongoDB, why it matters, and how it can make queries much faster — even with large datasets.

๐Ÿ“ Introduction

Imagine searching for a word in a 500-page book with no index — you’d have to flip through every page! Databases face the same issue without indexes.

Indexing helps databases find data faster, making queries more efficient — especially as data grows. In this part, you'll learn how indexing works in SQL and MongoDB, with practical tips to improve performance.


๐Ÿ”ธ 1. What is an Index in Databases?

An index is a data structure (often a B-tree or hash) that allows fast searching on specific columns or fields.

Without an index, databases perform a full scan, checking each row/document one by one — which is slow.

With an index, the database can jump directly to the matching data.


๐Ÿ”น 2. Indexing in SQL (e.g., MySQL/PostgreSQL)


Creating an Index

CREATE INDEX idx_student_name ON Students(Name);

Now, if you run this query:

SELECT * FROM Students WHERE Name = 'Aisha';

The database will use the idx_student_name index to quickly locate Aisha’s record.


๐Ÿ”ง Best Practices for SQL Indexing

  • Index columns used in WHERE, JOIN, and ORDER BY

  • Avoid indexing every column (slows down inserts/updates)

  • Use composite indexes when querying multiple columns


๐Ÿ”น 3. Indexing in MongoDB


Creating an Index

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

The 1 means ascending order. Now this query is much faster:

db.students.find({ name: "Aisha" });

๐Ÿง  MongoDB Index Types

  • Single field index – Basic fast lookup

  • Compound index – On multiple fields

  • Text index – For search in text fields

  • TTL index – For expiring data (e.g., sessions)


๐Ÿ”ง Best Practices for MongoDB Indexing

  • Use indexes on fields frequently used in queries

  • Avoid indexing large, low-selectivity fields (e.g., status = "active")

  • Monitor performance using explain() method

db.students.find({ name: "Aisha" }).explain("executionStats");

๐Ÿ“Š 4. Indexing Comparison: SQL vs MongoDB


Feature SQL MongoDB
Syntax CREATE INDEX createIndex()
Storage Separate B-tree structure B-tree by default
Types of Indexes Single, Unique, Composite Single, Compound, Text, TTL
Performance Insight EXPLAIN PLAN explain("executionStats")

๐Ÿง  Summary


Without Indexing With Indexing
Slow, full-table scans Fast, targeted lookups
Poor performance Scalable queries
Good for small data Essential for large data

Indexing is like giving your database a map — use it wisely for speed and efficiency.


✅ What’s Next?

In Part 9, we shall explore Relationships and Joins in SQL vs Referencing in NoSQL, so you can model complex data connections effectively.


    Click Next:
  • hands-on exercise for indexing and optimization



CRUD Operations in SQL vs MongoDB – Practice Task + Assignment for Beginners


๐Ÿงช Practice Task – CRUD Basics in SQL & MongoDB


Here's a Practice Task + Mini Assignment that complements Part 6: CRUD Operations in SQL vs NoSQL. It's designed to reinforce the differences in syntax and logic between SQL and MongoDB, while staying simple and highly practical for beginners.


๐ŸŽฏ Objective:

Perform basic Create, Read, Update, and Delete operations in both SQL and NoSQL (MongoDB).


๐Ÿ”น Scenario: School Students Data

You are managing a student database and need to do the following:

  1. Add a new student

  2. Fetch the student's data

  3. Update the student’s class

  4. Delete the student’s record


๐Ÿ“Œ A. SQL Practice

1. Create

INSERT INTO Students (StudentID, Name, Class)
VALUES (2, 'Ravi Kumar', '10B');

2. Read

SELECT * FROM Students WHERE StudentID = 2;

3. Update

UPDATE Students SET Class = '10C' WHERE StudentID = 2;

4. Delete

DELETE FROM Students WHERE StudentID = 2;


๐Ÿ“Œ B. MongoDB Practice

1. Create

db.students.insertOne({
  student_id: 2,
  name: "Ravi Kumar",
  class: "10B",
  marks: [{ subject: "English", score: 82 }]
});

2. Read

db.students.findOne({ student_id: 2 });

3. Update

db.students.updateOne(
  { student_id: 2 },
  { $set: { class: "10C" } }
);

4. Delete

db.students.deleteOne({ student_id: 2 });

๐Ÿ“ Mini Assignment: Build Your Own CRUD Set


๐Ÿ”น Instructions:

  1. Choose a student name and add them to both SQL and NoSQL.

  2. Add a subject and score for them (embedded in NoSQL).

  3. Read and display their data.

  4. Change their class and update their English score to 90.

  5. Finally, delete the record in both systems.


๐Ÿ’ก Challenge (Optional):

  • In SQL, insert marks into a separate Marks table and join it to fetch the student’s full profile.

  • In MongoDB, use $push to add a new subject to the marks array.


✅ Bonus: MongoDB $push Example

db.students.updateOne(
  { student_id: 2 },
  { $push: { marks: { subject: "Science", score: 88 } } }
);

Do you Know: The $push operator is used to add a new element to an array field in MongoDB.



Tell Us in Comments:

Which syntax do you find easier — SQL or MongoDB? Share your thoughts in the comments!

Also, Try the assignment above and share your solution in the comments.



To know about CRUD opreations read  Part 6: CRUD Operations in SQL vs NoSQL – A Beginner's Guide


✅ What’s Next?

Next: solution for the mini assignment in both SQL and NoSQL



CRUD Operations in SQL vs NoSQL Explained with Simple Examples

๐Ÿ”ท Part 6: CRUD Operations in SQL vs NoSQL – A Beginner's Guide


This post will:

  • ✅ Compare how to CreateReadUpdate, and Delete data in both systems

  • ✅ Use simple, realistic examples

  • ✅ Help beginners understand key syntax differences


๐Ÿ“ Introduction

In any application or system that works with data, you need to perform four basic operations:

  • Create new data

  • Read existing data

  • Update current data

  • Delete data you no longer need

These are called CRUD operations — and whether you're using SQL or NoSQL, they form the core of working with databases.

Let’s explore these operations in both SQL (like MySQL/PostgreSQL) and NoSQL (like MongoDB) with clear, side-by-side examples.


๐Ÿ”ธ Assumed Data Structure

We’ll use a simple students table/collection with:

  • StudentID

  • Name

  • Class

  • Marks (embedded in NoSQL)


๐Ÿ“Œ 1. CREATE – Inserting Data


✅ SQL (MySQL/PostgreSQL)

INSERT INTO Students (StudentID, Name, Class)
VALUES (1, 'Aisha', '10A');

✅ NoSQL (MongoDB)

db.students.insertOne({
  student_id: 1,
  name: "Aisha",
  class: "10A",
  marks: [
    { subject: "Math", score: 85 }
  ]
});

๐Ÿ“Œ 2. READ – Retrieving Data


✅ SQL

SELECT * FROM Students WHERE StudentID = 1;

✅ NoSQL

db.students.findOne({ student_id: 1 });

๐Ÿ“Œ 3. UPDATE – Changing Data


✅ SQL

UPDATE Students
SET Class = '10B'
WHERE StudentID = 1;

✅ NoSQL

db.students.updateOne(
  { student_id: 1 },
  { $set: { class: "10B" } }
);

๐Ÿ“Œ 4. DELETE – Removing Data


✅ SQL

DELETE FROM Students
WHERE StudentID = 1;

✅ NoSQL

db.students.deleteOne({ student_id: 1 });

๐Ÿ“Š Quick Comparison Table


Operation SQL Syntax MongoDB (NoSQL) Syntax
Create INSERT INTO ... VALUES (...) insertOne({ ... })
Read SELECT * FROM ... WHERE ... findOne({ ... })
Update UPDATE ... SET ... WHERE ... updateOne({ ... }, { $set: { ... } })
Delete DELETE FROM ... WHERE ... deleteOne({ ... })

๐Ÿง  Summary


SQL NoSQL (MongoDB)
Structured (tables/rows) Flexible (documents/JSON)
Uses SQL language Uses JavaScript-like syntax
Schema-based Schema-less
Great for complex queries Great for rapid, dynamic data

✅ What’s Next?

In Part 7, we’ll explore Normalization vs Denormalization — how SQL and NoSQL structure data differently for performance and flexibility.


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