Day 77

Database — MongoDB Basics

13 min
JavaScript 100 Days

MongoDB ek NoSQL database hai jisme data JSON-like documents mein store hota hai — tables ki jagah collections, rows ki jagah documents. Flexible schema se development fast hota hai.

MongoDB Concepts

Database, collection, document, field samjho.

mongodb-concepts.js
javascript
// MongoDB vs SQL comparison:
// Database    ← same
// Collection  ← Table
// Document    ← Row  
// Field       ← Column
// _id         ← Primary Key (auto-generated)

// Document example
{
  "_id": "ObjectId('...')",
  "name": "Zohaib Arshad",
  "email": "z@test.com",
  "age": 25,
  "skills": ["JavaScript", "React"],
  "address": {
    "city": "Lahore",
    "country": "Pakistan"
  },
  "createdAt": "ISODate(...)"
}

// Advantages of MongoDB:
// - Flexible schema — fields change ho sakte hain
// - JSON-like documents — JavaScript ke saath natural
// - Horizontal scaling (sharding)
// - Rich query language

MongoDB Shell Commands

Basic MongoDB operations.

mongo-commands.js
javascript
// MongoDB Compass ya mongosh mein run karo

// Database select/create
use myapp

// Collection mein insert
db.users.insertOne({
  name: "Zohaib",
  email: "z@test.com",
  age: 25
})

db.users.insertMany([
  { name: "Ali", age: 30 },
  { name: "Sara", age: 22 }
])

// Find documents
db.users.find()             // all
db.users.find({ age: 25 }) // filter
db.users.findOne({ email: "z@test.com" })

// Update
db.users.updateOne(
  { email: "z@test.com" },
  { $set: { age: 26 } }
)

// Delete
db.users.deleteOne({ email: "z@test.com" })

// Query operators
db.users.find({ age: { $gte: 18 } }) // age >= 18
db.users.find({ age: { $in: [22, 25, 30] } })

🎯 Practice Challenge

MongoDB Compass install karo. Students collection banao — 10 students insert karo. Queries practice karo — filter by age, sort by name.