https://github.com/devradheee/backend-
Welcome to my coding adventure! Iβm diving into backend development, sharing daily code snippets and mini-projects as I learn servers, APIs, and databases.
https://github.com/devradheee/backend-
expressjs mongodb nodejs
Last synced: about 2 months ago
JSON representation
Welcome to my coding adventure! Iβm diving into backend development, sharing daily code snippets and mini-projects as I learn servers, APIs, and databases.
- Host: GitHub
- URL: https://github.com/devradheee/backend-
- Owner: devradheee
- Created: 2025-08-25T20:33:53.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2025-08-25T21:10:56.000Z (10 months ago)
- Last Synced: 2025-08-25T22:29:59.568Z (10 months ago)
- Topics: expressjs, mongodb, nodejs
- Language: JavaScript
- Homepage: https://github.com/devradheee/backend-
- Size: 10.2 MB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
ο»Ώ# My Backend Development Journey π
Welcome to my coding adventure! Iβm diving into backend development, sharing daily code snippets and mini-projects as I learn servers, APIs, and databases.
---
## π― About
This repo is my learning diary, featuring:
- π Daily backend code
- π οΈ Small projects to solidify skills
- π Notes on my progress
---
## π οΈ Tech Stack
- **Languages**: JavaScript (Node.js)
- **Frameworks**: Express.js
- **Databases**: MongoDB
---
## π« Connect
- π [GitHub](https://github.com/devradheee)
- π¬ Open an issue for tips & discussions!
---
β¨ Happy coding! π»
# mongodb_1530
# MONGODB - Complete Guide
## Table of Contents
- [Introduction](#introduction)
- [Data vs Information](#data-vs-information)
- [What is a Database?](#what-is-a-database)
- [Types of Databases](#types-of-databases)
- [SQL Databases](#sql-databases)
- [NoSQL Databases](#nosql-databases)
- [SQL vs NoSQL](#sql-vs-nosql)
- [Scaling Strategies](#scaling-strategies)
- [Additional Resources](#additional-resources)
---
## Introduction
This guide provides a comprehensive overview of Database Management Systems, covering fundamental concepts, different database types, and scaling strategies. Whether you're a beginner or looking to refresh your knowledge, this document will help you understand how data is stored and managed in modern applications.
---
## Data vs Information
### Data
**Data** refers to raw, unprocessed facts and figures without context.
**Examples of Data:**
```
12, 34, 45
varun, ashwin, chetna
english, mathematics, science
```
These are just isolated values with no meaningful context.
### Information
**Information** is processed data that has meaning and context.
**Example of Information:**
```
"Varun scored 12 marks in the English exam"
```
Here, the raw data (12, varun, english) has been processed and combined to create meaningful information.
```
βββββββββββββββββββββββββββββββββββββββββββ
β DATA TO INFORMATION β
βββββββββββββββββββββββββββββββββββββββββββ€
β β
β Raw Data: β
β ββββββ¬βββββ¬βββββ¬βββββββββ¬ββββββββββ β
β β 12 β 34 β 45 β varun β english β β
β ββββββ΄βββββ΄βββββ΄βββββββββ΄ββββββββββ β
β β PROCESSING β β
β β
β Information: β
β "Varun scored 12 marks in English" β
β β
βββββββββββββββββββββββββββββββββββββββββββ
```
---
## What is a Database?
A **Database** is a container or organized collection where data can be stored, managed, and retrieved efficiently.
### CRUD Operations
Databases allow us to perform four fundamental operations:
- **C** - Create (Insert new data)
- **R** - Read (Retrieve/Query data)
- **U** - Update (Modify existing data)
- **D** - Delete (Remove data)
### Database Management System (DBMS)
A **DBMS** is software that enables users to perform CRUD operations on databases.
**Popular DBMS Examples:**
- MySQL
- Oracle SQL
- PostgreSQL
- MongoDB
- CouchDB
- Redis
```
ββββββββββββββββββββββββββββββββββββββββββββ
β DBMS Architecture β
ββββββββββββββββββββββββββββββββββββββββββββ€
β β
β User/Application β
β β β
β ββββββββββββββββ β
β β DBMS β β Manages operations β
β ββββββββββββββββ β
β β β
β ββββββββββββββββ β
β β Database β β Stores data β
β ββββββββββββββββ β
β β
ββββββββββββββββββββββββββββββββββββββββββββ
```
---
## Types of Databases
There are two primary ways to store and manage data:
### 1. SQL Databases
### 2. NoSQL Databases
---
## SQL Databases
**SQL** stands for **Structured Query Language**
### Key Characteristics:
1. **Tabular Structure**: Data is organized in tables with rows and columns
2. **Relational**: Also known as RDBMS (Relational Database Management System)
3. **Fixed Schema**: Must define table structure before inserting data
4. **Schema Enforcement**: Data must follow the predefined schema strictly
### SQL Database Structure Example:
```
ββββββββββββββββββββββββββββββββββββββββββββββββββ
β Students Table β
βββββββββββ¬βββββββββββ¬ββββββ¬ββββββββββββββββββββββ€
β ID β Name β Age β Subject β
βββββββββββΌβββββββββββΌββββββΌββββββββββββββββββββββ€
β 1 β Varun β 20 β English β
β 2 β Ashwin β 21 β Mathematics β
β 3 β Chetna β 22 β Science β
βββββββββββ΄βββββββββββ΄ββββββ΄ββββββββββββββββββββββ
Schema must be defined BEFORE data insertion:
- ID: Integer, Primary Key
- Name: String(50), Not Null
- Age: Integer
- Subject: String(50)
```
### Popular SQL Databases:
- **MySQL** - Most popular open-source database
- **PostgreSQL** - Advanced open-source database
- **Oracle SQL** - Enterprise-level database
- **Microsoft SQL Server** - Microsoft's database solution
- **SQLite** - Lightweight embedded database
### When to Use SQL:
- When data relationships are important
- When data integrity is critical
- For complex queries and transactions
- When ACID properties are required
- For structured, consistent data
---
## NoSQL Databases
**NoSQL** stands for **Not Only SQL**
### Key Characteristics:
1. **Flexible Storage**: Data can be stored in various formats
2. **Non-Relational**: Also known as Non-RDBMS
3. **Dynamic Schema**: No need to define structure beforehand
4. **Scalable**: Designed for horizontal scaling
---
## Four Categories of NoSQL Databases
### 1. Document-Based Databases
**Description**: Data is stored as JSON-like documents (BSON - Binary JSON)
**Examples**: MongoDB, CouchDB
**Structure Example:**
```javascript
// User A
{
"_id": "507f1f77bcf86cd799439011",
"name": "Varun",
"age": 20,
"email": "varun@example.com",
"subjects": ["English", "Math"]
}
// User B - Notice different structure
// (flexible schema)
{
"_id": "507f1f77bcf86cd799439012",
"name": "Ashwin",
"age": 21,
"phone": "+1234567890",
"address": {
"city": "Mumbai",
"country": "India"
}
}
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββ
β Document-Based Database β
ββββββββββββββββββββββββββββββββββββββββββ€
β Collection: Users β
β ββββββββββββββββββββββββββββββββββββ β
β β Document 1: β β
β β { name: "Varun", age: 20 } β β
β ββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββ β
β β Document 2: β β
β β { name: "Ashwin", age: 21, β β
β β email: "a@mail.com" } β β
β ββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββ
```
**Use Cases:**
- Content Management Systems
- E-commerce applications
- User profiles
- Catalogs
---
### 2. Key-Value Databases
**Description**: Data is stored as key-value pairs where each pair is independent
**Examples**: Redis, Amazon DynamoDB, Memcached
**Structure Example:**
```javascript
// Each entry is a separate key-value pair
"user:1000:name" β "Varun"
"user:1000:age" β "20"
"user:1000:email" β "varun@example.com"
"session:abc123" β { userId: 1000, loginTime: "2024-01-15", active: true }
"cache:products:123" β { productName: "Laptop", price: 50000 }
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββ
β Key-Value Database β
ββββββββββββββββββββββββββββββββββββββββββ€
β β
β Key β Value β
β βββββββββββββββββββββββββββββββββ β
β "user:100" β {...} β
β "session:abc123" β {...} β
β "cache:product:1" β {...} β
β "token:xyz789" β "jwt..." β
β β
ββββββββββββββββββββββββββββββββββββββββββ
```
**Use Cases:**
- Caching (most common)
- Session management
- Real-time data
- Shopping carts
- User preferences
---
### 3. Graph Databases
**Description**: Data is stored as nodes (entities) and edges (relationships)
**Examples**: Neo4j, Amazon Neptune, ArangoDB
**Structure Example:**
```
Nodes: Person, Company, City
Edges: WORKS_AT, LIVES_IN, FRIENDS_WITH
(Varun:Person)-[:WORKS_AT]->(TechCorp:Company)
(Varun:Person)-[:LIVES_IN]->(Mumbai:City)
(Varun:Person)-[:FRIENDS_WITH]->(Ashwin:Person)
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββ
β Graph Database β
ββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β (Varun) β
β β β
β β FRIENDS_WITH β
β β β
β (Ashwin)ββWORKS_AT --β(TechCorp) β
β β β
β β LIVES_IN β
β β β
β (Mumbai) β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Use Cases:**
- Social networks
- Recommendation engines
- Fraud detection
- Knowledge graphs
- Network topology
---
### 4. Wide-Column Databases
**Description**: Data is stored in columns rather than rows, optimized for queries over large datasets
**Examples**: Apache Cassandra, HBase, Google Bigtable
**Structure Example:**
```
Row Key: user_1000
ββ Column Family: personal_info
β ββ name: "Varun"
β ββ age: "20"
β ββ email: "varun@example.com"
ββ Column Family: academic_info
β ββ grade: "A"
β ββ subjects: ["English", "Math"]
β ββ gpa: "3.8"
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Wide-Column Database β
ββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Row Key β Column Family 1 β Column Family 2 β
β ββββββββββΌββββββββββββββββββββΌβββββββββββββββββ β
β user_1 β name: "Varun" β grade: "A" β
β β age: 20 β gpa: 3.8 β
β ββββββββββΌββββββββββββββββββββΌβββββββββββββββββ β
β user_2 β name: "Ashwin" β grade: "B+" β
β β age: 21 β gpa: 3.5 β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Use Cases:**
- Data analytics
- Time-series data
- IoT applications
- AI/ML model training
- Large-scale data warehousing
---
## SQL vs NoSQL
### Comprehensive Comparison Table
| Feature | SQL | NoSQL |
| ------------------ | ---------------------------------------------- | ----------------------------------------------- |
| **Data Structure** | Tables (rows & columns) | Documents, Key-Value, Graphs, Wide-Columns |
| **Schema** | Fixed, predefined schema required | Dynamic, flexible schema |
| **Scaling** | Vertical scaling (upgrade existing hardware) | Horizontal scaling (add more servers) |
| **Relationships** | Strong emphasis on data relationships | Relationships less important |
| **Data Integrity** | High (ACID properties) | Eventual consistency (BASE properties) |
| **Transactions** | Full ACID support | Limited transaction support |
| **Rollback** | Data rollback possible (UNDO) | Data rollback not typically available |
| **Query Language** | Standardized SQL | Varies by database |
| **Best For** | Complex queries, transactions, structured data | Large-scale data, flexibility, high performance |
---
## SQL Properties: ACID
```
βββββββββββββββββββββββββββββββββββββββββββββββ
β ACID Properties β
βββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β A - Atomicity β
β All or nothing - transaction β
β either completes fully or not at all β
β β
β C - Consistency β
β Data remains valid and follows β
β all defined rules and constraints β
β β
β I - Isolation β
β Concurrent transactions don't β
β interfere with each other β
β β
β D - Durability β
β Once committed, data persists β
β even after system failure β
β β
βββββββββββββββββββββββββββββββββββββββββββββββ
```
### ACID Example:
```sql
-- Bank Transfer Transaction
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;
-- If any step fails, entire transaction is rolled back
-- Ensuring money is neither lost nor duplicated
```
---
## NoSQL Properties: BASE
```
βββββββββββββββββββββββββββββββββββββββββββββββ
β BASE Properties β
βββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β BA - Basically Available β
β System guarantees availability β
β even if some parts fail β
β β
β S - Soft State β
β Data may be in inconsistent state β
β temporarily β
β β
β E - Eventually Consistent β
β Data will become consistent over β
β time, but not immediately β
β β
βββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## Scaling Strategies
**Scaling** refers to altering the size or capacity of a system to handle increased load.
### Vertical Scaling (Scale Up)
**Definition**: Adding more resources (CPU, RAM, Storage) to existing hardware
**Example:**
```javascript
// Before Scaling
let myLaptop = {
RAM: 16, // GB
HDD: 1024, // GB
CPU: 4, // cores
};
// After Vertical Scaling (Upgrading the SAME laptop)
let myLaptopUpgraded = {
RAM: 32, // Doubled RAM
HDD: 2048, // Doubled Storage
CPU: 8, // Doubled CPU cores
};
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββ
β Vertical Scaling β
ββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Before: β
β ββββββββββββββββ β
β β Server β β
β β RAM: 16GB β β
β β HDD: 1TB β β
β ββββββββββββββββ β
β β β
β UPGRADE β
β β β
β After: β
β ββββββββββββββββ β
β β Server β β
β β RAM: 32GB β β More powerful β
β β HDD: 2TB β β Same machine β
β ββββββββββββββββ β
β β
ββββββββββββββββββββββββββββββββββββββββββββββ
```
**Advantages:**
- Simpler to implement
- No application changes required
- Data consistency maintained
- Lower licensing costs
**Disadvantages:**
- Hardware limitations (can't scale indefinitely)
- Expensive high-end hardware
- Single point of failure
- Downtime during upgrades
**Best For:** SQL databases, traditional applications
---
### Horizontal Scaling (Scale Out)
**Definition**: Adding more machines/servers to the existing system
**Example:**
```javascript
// Existing System
let myLaptop = {
RAM: 16, // GB
HDD: 1024, // GB
CPU: 4, // cores
};
// After Horizontal Scaling (Adding NEW laptop)
let laptop1 = {
RAM: 16,
HDD: 1024,
CPU: 4,
};
let laptop2 = {
// NEW machine added
RAM: 16,
HDD: 1024,
CPU: 4,
};
// Total System Capacity = laptop1 + laptop2
```
**Visual Representation:**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β Horizontal Scaling β
βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Before: β
β ββββββββββββββββ β
β β Server 1 β β
β β RAM: 16GB β β
β ββββββββββββββββ β
β β
β β β
β ADD MORE SERVERS β
β β β
β After: β
β ββββββββββββββββ ββββββββββββββββ β
β β Server 1 β β Server 2 β β
β β RAM: 16GB β β RAM: 16GB β β New β
β ββββββββββββββββ ββββββββββββββββ β
β β β β
β ββββββββ¬ββββββββββββ β
β ββββ΄ββββββ β
β β Load β β
β βBalancerβ β
β ββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Advantages:**
- Virtually unlimited scaling
- Better fault tolerance (no single point of failure)
- Cost-effective (use commodity hardware)
- No downtime during scaling
**Disadvantages:**
- More complex architecture
- Data consistency challenges
- Network overhead
- Requires load balancing
**Best For:** NoSQL databases, cloud applications, microservices
---
## Comparison: Vertical vs Horizontal Scaling
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Scaling Strategy Comparison β
ββββββββββββββββββββ¬βββββββββββββββββββββ¬ββββββββββββββββββββ€
β Aspect β Vertical Scaling β Horizontal Scalingβ
ββββββββββββββββββββΌβββββββββββββββββββββΌββββββββββββββββββββ€
β Cost β High β Low to Medium β
β Complexity β Low β High β
β Downtime β Yes β No β
β Scalability β Limited β Unlimited β
β Fault Tolerance β Low β High β
β SQL Databases β β Preferred β β Difficult β
β NoSQL Databases β β Not ideal β β Preferred β
ββββββββββββββββββββ΄βββββββββββββββββββββ΄ββββββββββββββββββββ
```
---
## Decision Tree: Choosing the Right Database
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Database Selection Decision Tree β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Start
β
βββββββββββββ΄ββββββββββββ
β β
Is data highly Do you need
structured? flexibility?
β β
βββββ΄ββββ ββββββ΄βββββ
YES NO YES NO
β β β β
β β β β
Are ACID β Need to Consider
properties β scale SQL with
critical? β massively? careful
β β β planning
βββββ΄ββββ β βββββ΄ββββ
YES NO β YES NO
β β β β β
β β β β β
SQL β β β SQL or
β β NoSQL Document DB
β β β
β βββββββββββ΄ββββββββ β Evaluate:
β - Data relationships
β - Query patterns
β - Team expertise
β - Scale requirements
β
βββββββββββ Choose appropriate database type
```
---
## Real-World Use Cases
### E-Commerce Platform Example
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β E-Commerce System Architecture β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β User Authentication & Orders β β
β β Database: MySQL (SQL) β β
β β Reason: ACID properties for transactions β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β Product Catalog β β
β β Database: MongoDB (Document-based) β β
β β Reason: Flexible schema for varied productsβ β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β Session & Cache β β
β β Database: Redis (Key-Value) β β
β β Reason: Fast access, temporary data β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β Product Recommendations β β
β β Database: Neo4j (Graph) β β
β β Reason: Complex relationships β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## Best Practices
### For SQL Databases:
1. β
Normalize data to reduce redundancy
2. β
Create proper indexes for frequently queried columns
3. β
Use foreign keys to maintain referential integrity
4. β
Implement proper backup and recovery strategies
5. β
Optimize queries using EXPLAIN plans
6. β
Use transactions for multi-step operations
### For NoSQL Databases:
1. β
Design schema based on query patterns
2. β
Denormalize data for read performance
3. β
Use appropriate database type for use case
4. β
Implement application-level data validation
5. β
Plan for eventual consistency
6. β
Use caching strategically
---
## Common Database Operations
### SQL Example (MySQL):
```sql
-- Create Table (Schema Definition Required)
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
age INT,
subject VARCHAR(50)
);
-- Insert Data
INSERT INTO students (name, age, subject)
VALUES ('Varun', 20, 'English');
-- Read Data
SELECT * FROM students WHERE age > 18;
-- Update Data
UPDATE students SET age = 21 WHERE name = 'Varun';
-- Delete Data
DELETE FROM students WHERE id = 1;
```
### NoSQL Example (MongoDB):
```javascript
// No schema definition needed!
// Insert Document
db.students.insertOne({
name: "Varun",
age: 20,
subject: "English",
hobbies: ["reading", "coding"], // Flexible structure
});
// Read Documents
db.students.find({ age: { $gt: 18 } });
// Update Document
db.students.updateOne({ name: "Varun" }, { $set: { age: 21 } });
// Delete Document
db.students.deleteOne({ name: "Varun" });
```
---
## Summary
### Key Takeaways:
1. **Data vs Information**: Data is raw facts; information is processed data with meaning
2. **SQL Databases**:
- Structured, table-based storage
- Fixed schema, ACID properties
- Best for: Complex relationships, transactions, data integrity
3. **NoSQL Databases**:
- Flexible, document/key-value/graph/column storage
- Dynamic schema, BASE properties
- Best for: Scalability, flexibility, large datasets
4. **Scaling**:
- Vertical: Upgrade existing hardware (SQL-friendly)
- Horizontal: Add more machines (NoSQL-friendly)
5. **Choose Based On**:
- Data structure requirements
- Scalability needs
- Consistency requirements
- Team expertise
---
---
## MongoDB - Deep Dive
### What is MongoDB?
**MongoDB** is a document-based NoSQL database that stores data in JSON-like documents (BSON format) and is dynamic in nature.
**Key Characteristics:**
- Document-oriented storage
- Flexible schema (no predefined structure required)
- High performance and scalability
- Rich query language
- Built-in replication and sharding
```
ββββββββββββββββββββββββββββββββββββββββββββββββββ
β MongoDB Architecture β
ββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Application β
β β β
β βββββββ MongoDB Compass (GUI) β
β β β β
β βββββββ Mongo Shell (CLI) β
β β β β
β βββββββ Driver (Node.js/Python/etc.) β
β β β
β MongoDB Server β
β (mongodb://localhost:27017/) β
β β β
β ββββββββββββββββ β
β β Databases β β
β β Collections β β
β β Documents β β
β ββββββββββββββββ β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## MongoDB Installation
To work with MongoDB, you need to install three essential components:
### 1. MongoDB Community Server
**Purpose**: The core database server that stores and manages your data
**Download Link**:
```
https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-8.2.1-signed.msi
```
**What it does:**
- Runs the MongoDB database service
- Listens for connections on port 27017 (default)
- Stores all database files
- Provides the database engine
**Server Address**: `mongodb://localhost:27017/`
```
βββββββββββββββββββββββββββββββββββββββββββ
β MongoDB Community Server β
βββββββββββββββββββββββββββββββββββββββββββ€
β β
β β’ Core database engine β
β β’ Default port: 27017 β
β β’ Stores data on disk β
β β’ Handles queries and operations β
β β’ Manages connections β
β β
βββββββββββββββββββββββββββββββββββββββββββ
```
---
### 2. MongoDB Compass
**Purpose**: Graphical User Interface (GUI) for MongoDB
**Download Link**:
```
https://downloads.mongodb.com/compass/mongodb-compass-1.48.2-win32-x64.exe
```
**What it does:**
- Visual interface to interact with databases
- Perform CRUD operations without writing code
- View and analyze data visually
- Create and manage databases, collections
- Query builder and aggregation pipeline builder
**Important Note**:
- β Cannot insert JavaScript objects directly
- β
Only accepts JSON format for data insertion
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MongoDB Compass (GUI) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββββββββββββββββββββββββββββββββ β
β β Visual Interface β β
β β β’ Browse databases & collections β β
β β β’ Insert/Update/Delete documents β β
β β β’ Run queries visually β β
β β β’ View query performance β β
β β β’ Schema analysis β β
β β β’ Import/Export data β β
β βββββββββββββββββββββββββββββββββββββββββββββ β
β β
β Limitation: Only accepts JSON, not JS objects β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Example - Compass Data Entry:**
```json
// β
VALID in Compass (JSON format)
{
"name": "Varun",
"age": 20,
"subjects": ["English", "Math"]
}
// β INVALID in Compass (JavaScript object)
let user = {
name: "Varun",
age: 20,
subjects: ["English", "Math"]
};
```
---
### 3. Mongo Shell (mongosh)
**Purpose**: Command-Line Interface (CLI) for MongoDB
**Download Link**:
```
https://downloads.mongodb.com/compass/mongosh-2.5.9-x64.msi
```
**What it does:**
- Interactive shell to execute MongoDB commands
- Built using JavaScript
- Accepts both JavaScript objects and JSON
- Scripting and automation capabilities
- Advanced operations and administration
**Key Features:**
- β
Can insert JavaScript objects
- β
Can insert JSON data
- β
Full programmatic control
- β
Execute complex queries and operations
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Mongo Shell (mongosh) - CLI β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β $ mongosh β
β Current Mongosh Log ID: ... β
β Connecting to: mongodb://localhost:27017/ β
β Using MongoDB: 8.2.1 β
β β
β test> show dbs β
β test> use myDatabase β
β test> db.collection.insertOne({...}) β
β β
β Features: β
β β’ JavaScript-based shell β
β β’ Accepts JS objects and JSON β
β β’ Command history β
β β’ Auto-completion β
β β’ Scripting support β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Example - Shell Data Entry:**
```javascript
// β
VALID in Shell (JavaScript object)
db.students.insertOne({
name: "Varun",
age: 20,
subjects: ["English", "Math"],
});
// β
Also VALID in Shell (JSON format)
db.students.insertOne({
name: "Ashwin",
age: 21,
subjects: ["Science", "History"],
});
// β
VALID - Using variables (only in shell)
let newUser = {
name: "Chetna",
age: 22,
email: "chetna@example.com",
};
db.students.insertOne(newUser);
```
---
## MongoDB Components
### Component Comparison
| Component | Type | Code Required | Data Format | Best For |
| ------------------- | --------------- | ---------------- | ----------------- | ------------------------------------------ |
| **MongoDB Server** | Database Engine | N/A | BSON | Core database operations |
| **MongoDB Compass** | GUI | No | JSON only | Visual data exploration, beginners |
| **Mongo Shell** | CLI | Yes (JavaScript) | JSON + JS Objects | Advanced operations, scripting, developers |
---
## MongoDB Server Management
### Server Control Commands
The MongoDB server must be running for Compass and Shell to connect to it.
#### Starting and Stopping Server (Windows)
**Open Command Prompt as Administrator**, then use:
```bash
# Stop MongoDB Server
net stop mongodb
# Start MongoDB Server
net start mongodb
# Check MongoDB Service Status
sc query mongodb
```
**Visual Workflow:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MongoDB Server Management β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β 1. Open CMD as Administrator β
β Right-click CMD β Run as administrator β
β β
β 2. Stop Server β
β > net stop mongodb β
β The MongoDB Server service is stopping. β
β The MongoDB Server service was stopped. β
β β
β 3. Start Server β
β > net start mongodb β
β The MongoDB Server service is starting. β
β The MongoDB Server service was started. β
β β
β β οΈ Server must be running for connections! β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
### Using Mongo Shell (mongosh)
#### Entering the Shell
```bash
# Open regular Command Prompt (no admin rights needed)
> mongosh
# You'll see:
Current Mongosh Log ID: 65a1b2c3d4e5f6g7h8i9j0k1
Connecting to: mongodb://localhost:27017/?directConnection=true
Using MongoDB: 8.2.1
Using Mongosh: 2.5.9
test>
```
#### Exiting the Shell
```bash
# Method 1: Using exit command
test> .exit
# Method 2: Using keyboard shortcut
test> [Press Ctrl+C]
# Method 3: Using exit() function
test> exit()
```
**Shell Session Example:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Mongo Shell Session Example β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β $ mongosh β
β test> β Default database β
β β
β test> show dbs β List databases β
β admin 40.00 KiB β
β config 12.00 KiB β
β local 40.00 KiB β
β β
β test> use mySchool β Switch/create DB β
β switched to db mySchool β
β β
β mySchool> db.students.insertOne({ β
β ... name: "Varun", β
β ... age: 20 β
β ... }) β
β { β
β acknowledged: true, β
β insertedId: ObjectId('65a1b2c3d4e5f6g7h8i9j0') β
β } β
β β
β mySchool> .exit β Exit shell β
β $ β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## Quick Start Guide
### Step-by-Step Setup
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MongoDB Quick Start Workflow β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Step 1: Install Components β
β ββ Install MongoDB Community Server β
β ββ Install MongoDB Compass β
β ββ Install Mongo Shell (mongosh) β
β β
β Step 2: Start MongoDB Server β
β ββ Open CMD as Admin β net start mongodb β
β β
β Step 3: Choose Your Interface β
β ββ Option A: MongoDB Compass (GUI) β
β β ββ Connect to: mongodb://localhost:27017/ β
β β β
β ββ Option B: Mongo Shell (CLI) β
β ββ Open CMD β Type: mongosh β
β β
β Step 4: Start Working with Data β
β ββ Create databases β
β ββ Create collections β
β ββ Insert documents β
β ββ Query and manipulate data β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## MongoDB vs SQL Terminology
| SQL Term | MongoDB Equivalent | Description |
| ----------- | ------------------ | ------------------------------------ |
| Database | Database | Container for collections |
| Table | Collection | Container for documents |
| Row | Document | Single record (JSON-like) |
| Column | Field | Single data element |
| Primary Key | \_id | Unique identifier (auto-generated) |
| Index | Index | Performance optimization |
| JOIN | Embedding/$lookup | Combining data from multiple sources |
**Visual Comparison:**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SQL vs MongoDB Structure β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β SQL Database: β
β ββ Students Table β
β ββ Row 1: id=1, name="Varun", age=20 β
β ββ Row 2: id=2, name="Ashwin", age=21 β
β ββ Row 3: id=3, name="Chetna", age=22 β
β β
β MongoDB Database: β
β ββ students Collection β
β ββ Document 1: {_id: ..., name: "Varun", age: 20} β
β ββ Document 2: {_id: ..., name: "Ashwin", age: 21} β
β ββ Document 3: {_id: ..., name: "Chetna", age: 22} β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## Connection String Format
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MongoDB Connection String β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β mongodb://localhost:27017/ β
β βββ¬ββ ββββββ¬βββββ βββ¬ββ β
β β β β β
β β β ββ Port number β
β β βββββββββββ Host (localhost = your PC) β
β ββββββββββββββββββββββ Protocol β
β β
β Full format with options: β
β mongodb://username:password@host:port/database?optionsβ
β β
β Examples: β
β β’ mongodb://localhost:27017/ β
β β’ mongodb://localhost:27017/myDatabase β
β β’ mongodb://user:pass@localhost:27017/myDB β
β β’ mongodb://192.168.1.100:27017/ β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## Key Differences: Compass vs Shell
### MongoDB Compass (GUI)
**Advantages:**
- β
User-friendly visual interface
- β
No coding knowledge required
- β
Great for beginners
- β
Easy data visualization
- β
Point-and-click operations
- β
Built-in query builder
**Limitations:**
- β Only accepts JSON format
- β Cannot use JavaScript variables
- β Limited scripting capabilities
- β Slower for bulk operations
**Best For:**
- Quick data exploration
- Beginners learning MongoDB
- Visual schema analysis
- One-off manual operations
---
### Mongo Shell (CLI)
**Advantages:**
- β
Accepts JavaScript objects and JSON
- β
Full programming capabilities
- β
Can use variables and functions
- β
Scripting and automation
- β
Faster for bulk operations
- β
More powerful and flexible
**Limitations:**
- β Requires command-line knowledge
- β Steeper learning curve
- β No visual interface
- β Text-based only
**Best For:**
- Advanced operations
- Automation and scripting
- Development and testing
- Bulk operations
- Production management
---
## MongoDB Installation Checklist
```markdown
### Installation Verification Checklist
β‘ MongoDB Community Server installed
ββ Verify: Open Services β Find "MongoDB Server"
β‘ MongoDB Compass installed
ββ Verify: Launch Compass β See connection screen
β‘ Mongo Shell (mongosh) installed
ββ Verify: Open CMD β Type "mongosh --version"
β‘ MongoDB Server is running
ββ Verify: CMD (Admin) β "sc query mongodb"
Look for "STATE: RUNNING"
β‘ Can connect via Compass
ββ Verify: Open Compass β Connect to localhost:27017
Should see "admin", "config", "local" databases
β‘ Can connect via Shell
ββ Verify: CMD β "mongosh"
Should see connection success message
β
All checks passed? You're ready to start using MongoDB!
```
---
## Common Issues and Solutions
### Issue 1: Cannot Connect to Server
```javascript
β Error: connect ECONNREFUSED 127.0.0.1:27017
β
Solution:
1. Check if MongoDB Server is running
CMD (Admin) β net start mongodb
2. Check if port 27017 is available
CMD β netstat -ano | findstr :27017
3. Check firewall settings
```
### Issue 2: mongosh Command Not Found
```javascript
β Error: 'mongosh' is not recognized
β
Solution:
1. Verify installation
Check: C:\Program Files\mongosh\
2. Add to PATH environment variable
System Properties β Environment Variables
β Add mongosh bin directory to PATH
3. Restart Command Prompt
```
### Issue 3: Access Denied When Starting Server
```javascript
β Error: Access is denied
β
Solution:
1. Run Command Prompt as Administrator
Right-click CMD β "Run as administrator"
2. Then execute: net start mongodb
```
---
## Summary
### Key Takeaways:
1. **MongoDB** is a document-based NoSQL database storing data as JSON-like documents
2. **Three Components** needed:
- **MongoDB Server**: The database engine (mongodb://localhost:27017/)
- **MongoDB Compass**: GUI for visual data management (JSON only)
- **Mongo Shell**: CLI for programmatic access (JavaScript + JSON)
3. **Server Management**:
- Start: `net start mongodb` (Admin CMD)
- Stop: `net stop mongodb` (Admin CMD)
4. **Shell Commands**:
- Enter: `mongosh`
- Exit: `.exit` or `Ctrl+C`
5. **Compass vs Shell**:
- Compass: User-friendly, JSON only, visual interface
- Shell: More powerful, JavaScript support, automation
6. **Data Format**:
- Compass: JSON format only
- Shell: Both JavaScript objects and JSON
---
## Summary
### Key Takeaways:
1. **Data vs Information**: Data is raw facts; information is processed data with meaning
2. **SQL Databases**:
- Structured, table-based storage
- Fixed schema, ACID properties
- Best for: Complex relationships, transactions, data integrity
3. **NoSQL Databases**:
- Flexible, document/key-value/graph/column storage
- Dynamic schema, BASE properties
- Best for: Scalability, flexibility, large datasets
4. **Scaling**:
- Vertical: Upgrade existing hardware (SQL-friendly)
- Horizontal: Add more machines (NoSQL-friendly)
5. **Choose Based On**:
- Data structure requirements
- Scalability needs
- Consistency requirements
- Team expertise
---
## MongoDB Shell Commands
This section covers essential MongoDB shell commands for database and collection management.
### Understanding the `db` Object
```javascript
// What is db?
typeof db; // Returns: "object"
// db is a JavaScript object that represents the current database
// It provides methods to interact with the database
```
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Understanding the 'db' Object β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β db = { β
β // Current database reference β
β // Provides methods for operations: β
β createCollection(), β
β dropDatabase(), β
β getCollectionNames(), β
β // ... and many more β
β } β
β β
β Usage Example: β
β test> db // Shows current DBβ
β test> typeof db // Returns: object β
β test> db.getName() // Returns: test β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
### 1. Listing All Databases
**Command:**
```javascript
show dbs
// OR
show databases
```
**Description**: Lists all databases present on the MongoDB server with their sizes
**Example Output:**
```
admin 40.00 KiB
config 12.00 KiB
local 40.00 KiB
library 80.00 KiB
school 56.00 KiB
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β show dbs / show databases β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Command: show dbs β
β β
β MongoDB Server β
β ββ admin (40 KiB) β System database β
β ββ config (12 KiB) β Configuration data β
β ββ local (40 KiB) β Local server data β
β ββ library (80 KiB) β User database β
β ββ school (56 KiB) β User database β
β β
β Note: Empty databases won't appear in the list β
β until they contain at least one collection β
β with data β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Important Notes:**
- **System Databases**: `admin`, `config`, and `local` are system databases created by MongoDB
- **Empty Databases**: Won't appear in the list until they have at least one collection with data
- **Size Display**: Shows the disk space used by each database
---
### 2. Creating/Switching Database
**Command:**
```javascript
use database_name
```
**Description**: Creates a new database or switches to an existing database
**Example:**
```javascript
// Create/Switch to library database
test> use library
switched to db library
library> // Notice the prompt changed
```
**How it Works:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β use database_name β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Scenario 1: Database EXISTS β
β βββββββββββββββββββββββββββββ β
β use library β
β β β
β Switches to 'library' database β
β Prompt: library> β
β β
β Scenario 2: Database DOES NOT EXIST β
β ββββββββββββββββββββββββββββββββββββββ β
β use newDatabase β
β β β
β Creates 'newDatabase' in memory β
β Prompt: newDatabase> β
β β β
β β οΈ Database won't be saved until: β
β 1. You create a collection β
β 2. You insert data into a collection β
β β
β Example: β
β newDatabase> show dbs β
β (newDatabase won't appear yet) β
β β
β newDatabase> db.createCollection("users") β
β newDatabase> show dbs β
β (newDatabase now appears in the list) β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Practical Example:**
```javascript
// Step 1: Create/Switch to new database
test> use myShop
switched to db myShop
// Step 2: Check databases (myShop won't appear)
myShop> show dbs
admin 40 KiB
config 12 KiB
local 40 KiB
// myShop is NOT listed yet
// Step 3: Create a collection
myShop> db.createCollection("products")
{ ok: 1 }
// Step 4: Check databases again (myShop appears)
myShop> show dbs
admin 40 KiB
config 12 KiB
local 40 KiB
myShop 8 KiB // β Now it appears!
```
---
### 3. Understanding the Default Database
**Default Database**: `test`
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Default Database: 'test' β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β When you start mongosh: β
β β
β $ mongosh β
β Connecting to: mongodb://localhost:27017/ β
β Using MongoDB: 8.2.1 β
β β
β test> β Shell prompt shows current database β
β β
β The prompt always indicates which database β
β you're currently working with: β
β β
β test> β Working with 'test' database β
β library> β Working with 'library' database β
β school> β Working with 'school' database β
β β
β To check current database: β
β test> db β
β test β
β β
β test> db.getName() β
β test β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
### 4. Creating a Collection
**Command:**
```javascript
db.createCollection("collection_name");
```
**Description**: Creates a new collection within the current database
**Example:**
```javascript
// Create a 'books' collection
library > db.createCollection("books");
{
ok: 1;
}
// Create multiple collections
library > db.createCollection("authors");
{
ok: 1;
}
library > db.createCollection("publishers");
{
ok: 1;
}
```
**Return Value:**
- `{ ok: 1 }` - Collection created successfully
- `{ ok: 0 }` - Error occurred (with error message)
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β db.createCollection() β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β library> db.createCollection("books") β
β β
β MongoDB Server β
β ββ library (database) β
β ββ books (collection) β NEW β
β ββ (empty collection created) β
β β
β Response: { ok: 1 } β
β β
β ββββββββββββββββββββββββββββββββββββββββββββ β
β β Collection Structure β β
β β β β
β β books: [ β β
β β // Documents will go here β β
β β // Currently empty β β
β β ] β β
β ββββββββββββββββββββββββββββββββββββββββββββ β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Advanced Options:**
```javascript
// Create collection with options
db.createCollection("users", {
capped: true, // Fixed-size collection
size: 5242880, // Max size in bytes (5MB)
max: 5000, // Max number of documents
});
// Create collection with validation
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required",
},
price: {
bsonType: "number",
minimum: 0,
description: "must be a number and is required",
},
},
},
},
});
```
---
### 5. Listing All Collections
**Command:**
```javascript
show collections
```
**Description**: Displays all collections present in the current database
**Example:**
```javascript
library> show collections
books
authors
publishers
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β show collections β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β library> show collections β
β β
β Current Database: library β
β ββ books β Collection 1 β
β ββ authors β Collection 2 β
β ββ publishers β Collection 3 β
β β
β Alternative commands: β
β β’ db.getCollectionNames() β
β β’ db.getCollectionInfos() (detailed info) β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Alternative Methods:**
```javascript
// Method 1: Get array of collection names
library> db.getCollectionNames()
[ 'books', 'authors', 'publishers' ]
// Method 2: Get detailed collection information
library> db.getCollectionInfos()
[
{
name: 'books',
type: 'collection',
options: {},
info: {
readOnly: false,
uuid: UUID("...")
},
idIndex: { v: 2, key: { _id: 1 }, name: '_id_' }
},
// ... more collections
]
// Method 3: Get collection count
library> db.getCollectionNames().length
3
```
---
### 6. Practical Exercise - Creating School Database
**Task**: Create a school database with three collections
```javascript
// Step 1: Create/Switch to school database
test> use school
switched to db school
// Step 2: Create students collection
school> db.createCollection("students")
{ ok: 1 }
// Step 3: Create teachers collection
school> db.createCollection("teachers")
{ ok: 1 }
// Step 4: Create otherStaff collection
school> db.createCollection("otherStaff")
{ ok: 1 }
// Step 5: Verify collections
school> show collections
students
teachers
otherStaff
```
**Visual Result:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β School Database Structure β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β MongoDB Server β
β ββ school (database) β
β ββ students (collection) β
β ββ teachers (collection) β
β ββ otherStaff (collection) β
β β
β All collections are empty and ready for data β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
### 7. Shell Shortcuts and Tips
**Productivity Tips:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MongoDB Shell Shortcuts β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β 1. TAB Completion β
β Type partial command + TAB β
β Example: db.cr[TAB] β db.createCollection() β
β β
β 2. Command History β
β β (Up Arrow) - Previous command β
β β (Down Arrow) - Next command β
β β
β 3. Clear Screen β
β Method 1: Type 'cls' β
β Method 2: Press Ctrl + L β
β β
β 4. Multi-line Commands β
β Press Enter to continue on next line β
β mongosh waits for complete command β
β β
β 5. Help Commands β
β help - General help β
β db.help() - Database methods β
β db.collection.help() - Collection methods β
β β
β 6. Exit Shell β
β .exit OR Ctrl+C OR exit() β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Practical Examples:**
```javascript
// Tab completion example
test> db.cre[TAB]
// Autocompletes to: db.createCollection
test> db.c[TAB][TAB]
// Shows all methods starting with 'c':
// createCollection createView currentOp...
// Multi-line command example
test> db.createCollection(
... "users",
... { capped: true }
... )
{ ok: 1 }
// Help commands
test> help
Shell Help:
use Set current database
show Show databases/collections
exit Exit the shell
...
test> db.help()
Database Class:
db.createCollection() Create a new collection
db.dropDatabase() Delete the database
...
test> db.students.help()
Collection Class:
db.collection.insertOne() Insert a document
db.collection.find() Find documents
...
```
---
### 8. Renaming a Collection
**Command:**
```javascript
db.collection_name.renameCollection("new_collection_name");
```
**Description**: Renames an existing collection to a new name
**Example:**
```javascript
// Rename 'otherStaff' to 'faculty'
school> db.otherStaff.renameCollection("faculty")
{ ok: 1 }
// Verify the change
school> show collections
students
teachers
faculty // β Renamed from otherStaff
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β renameCollection() β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β BEFORE: β
β school (database) β
β ββ students β
β ββ teachers β
β ββ otherStaff β Target collection β
β β
β Command: β
β db.otherStaff.renameCollection("faculty") β
β β
β AFTER: β
β school (database) β
β ββ students β
β ββ teachers β
β ββ faculty β Renamed collection β
β β
β β
All documents preserved β
β β
All indexes preserved β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Important Notes:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β renameCollection() - Important Notes β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β β
WHAT IS PRESERVED: β
β β’ All documents in the collection β
β β’ All indexes β
β β’ Collection metadata β
β β
β β οΈ LIMITATIONS: β
β β’ Cannot rename across databases β
β β’ Target name must not already exist β
β β’ Cannot rename system collections β
β β’ Requires appropriate permissions β
β β
β β WILL FAIL IF: β
β β’ Target collection name already exists β
β β’ Source collection doesn't exist β
β β’ Insufficient permissions β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Error Handling:**
```javascript
// Example: Trying to rename to existing collection
school> db.students.renameCollection("teachers")
MongoServerError: target namespace exists
// β Fails because 'teachers' already exists
// Example: Renaming non-existent collection
school> db.nonExistent.renameCollection("newName")
MongoServerError: source namespace does not exist
// β Fails because 'nonExistent' doesn't exist
// β
Correct: Rename to a new, unused name
school> db.students.renameCollection("pupils")
{ ok: 1 }
```
**Advanced Usage:**
```javascript
// Rename with dropTarget option (overwrites if exists)
db.oldCollection.renameCollection("newCollection", { dropTarget: true });
// This will:
// 1. Drop 'newCollection' if it exists
// 2. Rename 'oldCollection' to 'newCollection'
// β οΈ Use with caution - data loss possible!
```
---
### 9. Important Note: Renaming Databases
**Key Limitation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DATABASE RENAMING NOT SUPPORTED β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β β MongoDB does NOT support renaming databases β
β β
β Why? β
β β’ Database names are part of file system paths β
β β’ Would require moving large data files β
β β’ Could cause data corruption β
β β’ Complex operation with many edge cases β
β β
β Workaround: β
β If you need to "rename" a database: β
β β
β 1. Create new database with desired name β
β 2. Copy all collections to new database β
β 3. Verify data integrity β
β 4. Drop old database β
β β
β β οΈ This is manual and time-consuming for large β
β databases! β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Manual Database "Rename" Process:**
```javascript
// Step 1: Create new database
use newDatabaseName
// Step 2: Copy collections (manual process)
// For each collection in old database:
db.oldDB.collection1.find().forEach(function(doc) {
db.collection1.insert(doc);
});
// OR use aggregation pipeline (faster for large collections)
db.oldDB.collection1.aggregate([
{ $out: "newDatabaseName.collection1" }
]);
// Step 3: Verify data
use newDatabaseName
db.collection1.countDocuments() // Compare with old count
// Step 4: Drop old database
use oldDatabaseName
db.dropDatabase()
```
**Better Approach - Plan Database Names Carefully:**
```javascript
// β
GOOD PRACTICE: Choose meaningful names from the start
use productionDB // Clear, descriptive
use ecommerce_prod // Environment-specific
use myapp_v2 // Version-specific
// β AVOID: Generic or temporary names
use test // Too generic
use temp_db // Implies temporary
use db1 // Not descriptive
```
---
### 10. Deleting a Collection
**Command:**
```javascript
db.collection_name.drop();
```
**Description**: Permanently deletes a collection and all its documents
**Example:**
```javascript
// Delete the 'faculty' collection
school> db.faculty.drop()
true // Returns true if successful
// Verify deletion
school> show collections
students
teachers
// faculty is gone
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β db.collection.drop() β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β BEFORE: β
β school (database) β
β ββ students β
β ββ teachers β
β ββ faculty β Target for deletion β
β β
β Command: β
β db.faculty.drop() β
β β
β AFTER: β
β school (database) β
β ββ students β
β ββ teachers β
β β
β β faculty collection completely removed β
β β All documents in faculty are deleted β
β β All indexes are deleted β
β β οΈ THIS OPERATION CANNOT BE UNDONE! β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Return Values:**
```javascript
// Success - collection existed and was dropped
school > db.faculty.drop();
true;
// Collection doesn't exist
school > db.nonExistent.drop();
false;
// Cannot drop system collections
school > db.system.indexes.drop();
false;
```
**Important Warnings:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β drop() - Critical Warnings β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β β οΈ PERMANENT DELETION β
β β’ Cannot be undone β
β β’ No confirmation prompt β
β β’ Immediate effect β
β β
β β WHAT IS DELETED: β
β β’ All documents in the collection β
β β’ All indexes on the collection β
β β’ Collection metadata β
β β
β π‘ BEST PRACTICES: β
β 1. Always backup before dropping β
β 2. Double-check collection name β
β 3. Verify you're in correct database β
β 4. Consider archiving data first β
β β
β π PRODUCTION SAFETY: β
β β’ Restrict drop permissions β
β β’ Use backup/restore procedures β
β β’ Implement soft-delete patterns β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Safe Deletion Pattern:**
```javascript
// Step 1: Verify you're in the correct database
db.getName()
// Ensure it shows the database you intend
// Step 2: Check collection exists and view sample data
db.faculty.findOne()
// Review to ensure it's the right collection
// Step 3: Count documents (optional backup decision)
db.faculty.countDocuments()
// If many documents, consider backing up first
// Step 4: Backup (if needed)
// Export to JSON file using mongodump or mongoexport
// Step 5: Drop the collection
db.faculty.drop()
// Step 6: Verify deletion
show collections
// Confirm faculty is not in the list
```
---
### 11. Deleting a Database
**Command:**
```javascript
db.dropDatabase();
```
**Description**: Permanently deletes the current database and all its collections
**Example:**
```javascript
// Switch to the database you want to delete
test> use school
switched to db school
// Delete the entire database
school> db.dropDatabase()
{ ok: 1, dropped: 'school' }
// Verify deletion
school> show dbs
admin 40 KiB
config 12 KiB
local 40 KiB
// school is gone
// Note: Prompt still shows 'school' but database is deleted
school> show collections
// No collections (database is empty/deleted)
```
**Visual Representation:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β db.dropDatabase() β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β BEFORE: β
β MongoDB Server β
β ββ admin β
β ββ config β
β ββ local β
β ββ school β Target database β
β ββ students (collection) β
β ββ teachers (collection) β
β ββ faculty (collection) β
β β
β Command: (while in school database) β
β db.dropDatabase() β
β β
β AFTER: β
β MongoDB Server β
β ββ admin β
β ββ config β
β ββ local β
β β
β β school database completely removed β
β β All collections deleted β
β β All documents deleted β
β β All indexes deleted β
β β οΈ THIS OPERATION CANNOT BE UNDONE! β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Return Values:**
```javascript
// Success - database existed and was dropped
school> db.dropDatabase()
{ ok: 1, dropped: 'school' }
// Database was already empty/deleted
test> db.dropDatabase()
{ ok: 1 }
// Note: No 'dropped' field if database didn't exist
// Cannot drop system databases (protected)
admin> db.dropDatabase()
MongoServerError: cannot drop admin database
```
**Critical Warnings:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β dropDatabase() - EXTREME CAUTION β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β π¨ NUCLEAR OPTION - USE WITH EXTREME CARE β
β β
β β οΈ PERMANENT DELETION OF: β
β β’ Entire database β
β β’ ALL collections in the database β
β β’ ALL documents in all collections β
β β’ ALL indexes β
β β’ ALL metadata β
β β
β β NO UNDO - NO RECOVERY - NO CONFIRMATION β
β β
β π‘ WHEN TO USE: β
β β’ Development/testing environments β
β β’ Cleaning up temporary databases β
β β’ Complete reset required β
β β
β π PRODUCTION GUIDELINES: β
β 1. NEVER use in production without backup β
β 2. Restrict permissions strictly β
β 3. Implement approval workflows β
β 4. Use database versioning β
β 5. Consider soft-delete alternatives β
β β
β β
SAFE ALTERNATIVES: β
β β’ Drop individual collections instead β
β β’ Archive data before deletion β
β β’ Use backup/restore procedures β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Safe Database Deletion Procedure:**
```javascript
// ===== PRODUCTION-SAFE DATABASE DELETION =====
// Step 1: Verify current database
db.getName()
// Output: school
// β Confirm this is the database you want to delete
// Step 2: List all collections
show collections
// Review all collections that will be deleted
// Step 3: Check database size
db.stats()
// Review dataSize, storageSize, indexSize
// Decide if backup is needed
// Step 4: Count total documents (optional)
let totalDocs = 0;
db.getCollectionNames().forEach(function(col) {
let count = db[col].countDocuments();
print(col + ": " + count + " documents");
totalDocs += count;
});
print("Total documents: " + totalDocs);
// Step 5: Backup (CRITICAL for production)
// Use mongodump in separate terminal:
// $ mongodump --db=school --out=/backup/path
// Step 6: Final confirmation check
db.getName()
// One last check before deletion
// Step 7: Drop the database
db.dropDatabase()
// Step 8: Verify deletion
show dbs
// Confirm 'school' is not in the list
// Step 9: Switch to another database
use admin
// Good practice: don't stay in deleted database context
```
**Common Mistakes to Avoid:**
```javascript
// β MISTAKE 1: Wrong database
test> db.dropDatabase()
// Dropped 'test' instead of intended database!
// β
CORRECT:
test> use school
school> db.getName() // Verify
school
school> db.dropDatabase()
// β MISTAKE 2: No backup
production> db.dropDatabase()
// All data lost forever!
// β
CORRECT:
// Always backup first in production
// $ mongodump --db=production
// β MISTAKE 3: Dropping system databases
admin> db.dropDatabase()
// MongoDB prevents this, but don't attempt
// β
CORRECT:
// Never drop admin, config, or local databases
```
---
### 12. Syncing Shell Changes with Compass
**Important Note:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Refreshing MongoDB Compass β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β After performing operations in the shell, β
β MongoDB Compass does NOT auto-refresh β
β β
β Manual Refresh Required: β
β β’ Click the refresh button in Compass β
β β’ Or press F5 β
β β’ Or reconnect to the database β
β β
β Why? β
β β’ Compass and Shell are separate applications β
β β’ Both connect to the same MongoDB server β
β β’ Changes made in one don't auto-update the other β
β β
β Workflow: β
β 1. Make changes in Shell (create/drop/etc.) β
β 2. Switch to Compass β
β 3. Click refresh button β
β 4. See updated data β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
**Visual Workflow:**
```
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Shell & Compass Synchronization β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Mongo