Introduction to MongoDB
Table of Contents
1. Introduction & Architecture
============================================================
WHAT IS MONGODB?
============================================================
MongoDB is an open-source, NoSQL, document-oriented database.
Instead of tables and rows (like MySQL/PostgreSQL), MongoDB stores data in flexible, JSON-like documents called BSON (Binary JSON).
============================================================
ARCHITECTURE OVERVIEW
============================================================
1. Application Layer:
Applications connect using MongoDB Drivers (Node.js, Python, Java, etc.).
2. Database Engine (mongod):
The primary background daemon process handling requests, data access,
and background operations.
3. Storage Engine (WiredTiger - Default):
Manages how data and indexes are saved to physical memory and disk.
Provides document-level concurrency and data compression.
4. Scalability & High Availability:
- Replica Sets: Primary/Secondary cluster for automatic failover.
- Sharding: Horizontal partitioning to distribute large datasets across multiple nodes.
2. MongoDB Tools & Ecosystem
# 1. mongosh (MongoDB Shell)
# The modern, interactive command-line interface for querying and admin tasks.
mongosh "mongodb://localhost:27017"
# 2. MongoDB Compass
# The official GUI (Graphical User Interface) for querying, visualizing data,
# and managing indexes without writing CLI commands.
# 3. MongoDB Command-Line Database Tools:
# Export and Import collections (JSON / CSV)
mongoexport --db=shop --collection=users --out=users.json
mongoimport --db=shop --collection=users --file=users.json
# Backup and Restore entire databases (Binary BSON format)
mongodump --db=shop --out=/backups/
mongorestore --db=shop /backups/shop/
# 4. MongoDB Atlas
# The official fully managed cloud database service (AWS, Azure, GCP).
3. Core Concepts: Database, Collection, Documents
// ============================================================
// SQL vs. MongoDB Terminology Mapping
// ============================================================
// Relational (SQL) | MongoDB (NoSQL)
// ------------------------+--------------------
// Database | Database
// Table | Collection
// Row | Document (BSON)
// Column | Field
// Primary Key (PK) | _id (ObjectId by default)
// JOIN | $lookup / Embedded Documents
// ============================================================
// SAMPLE MONGODB DOCUMENT STRUCTURE
// ============================================================
{
"_id": ObjectId("64f1a2b3c4d5e6f7a8b9c0d1"), // Unique Identifier
"name": "Alice Johnson", // String field
"age": 28, // Number (Integer) field
"is_active": true, // Boolean field
"skills": ["JavaScript", "Python", "Docker"], // Array field
"address": { // Embedded / Sub-Document
"city": "San Francisco",
"country": "USA"
}
}
4. Supported Data Types (BSON)
// MongoDB stores data as BSON, supporting standard JSON types + extended types:
1. String: UTF-8 text -> "Hello World"
2. Integer: 32-bit or 64-bit integer -> NumberInt(42) / NumberLong(90000000)
3. Double: Floating point numbers -> 19.99
4. Boolean: Logical true or false -> true / false
5. Array: List of values/objects -> ["admin", "editor"]
6. Object: Embedded/Nested document -> { "zip": 94107 }
7. ObjectId: 12-byte unique key -> ObjectId("...")
8. Date: UTC DateTime -> new Date() / ISODate("2024-01-01")
9. Null: Empty/Undefined value -> null
10. Binary Data:Images, files, or blobs -> BinData(...)
5. Mongo Shell (`mongosh`) & CRUD Operations
// ============================================================
// STEP 1: Connect & Select Database
// ============================================================
//Connect
mongosh "mongodb://localhost:27017" // Switch or automatically create database use myStore; // Show current active database db; // ============================================================ // STEP 2: CREATE / INSERT // ============================================================ // Insert a single document db.products.insertOne({ name: "Wireless Mouse", price: 29.99, category: "Electronics", stock: 150, tags: ["gadgets", "computers"] }); // Insert multiple documents db.products.insertMany([ { name: "Mechanical Keyboard", price: 89.99, category: "Electronics", stock: 50 }, { name: "Coffee Mug", price: 12.50, category: "Kitchen", stock: 200 }, { name: "USB-C Cable", price: 9.99, category: "Electronics", stock: 0 } ]); // ============================================================ // STEP 3: READ / FIND // ============================================================ // Find all documents in a collection db.products.find(); // Find with exact match filter db.products.find({ category: "Electronics" }); // Find with comparison operators ($gt, $gte, $lt, $lte, $in) db.products.find({ price: { $gt: 20 } }); // Find with Projection (Include: 1, Exclude: 0) // Returns only name and price (excludes _id) db.products.find( { category: "Electronics" }, { name: 1, price: 1, _id: 0 } ); // ============================================================ // STEP 4: UPDATE // ============================================================ // Update a single document ($set updates fields without overwriting the whole document) db.products.updateOne( { name: "Wireless Mouse" }, { $set: { price: 24.99, stock: 140 } } ); // Update multiple documents db.products.updateMany( { category: "Electronics" }, { $set: { on_sale: true } } ); // ============================================================ // STEP 5: DELETE // ============================================================ // Delete a single matching document db.products.deleteOne({ name: "Coffee Mug" }); // Delete multiple matching documents db.products.deleteMany({ stock: 0 }); // Delete all documents in a collection (keeps the collection) db.products.deleteMany({}); Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.
Thank you
Rajasekhar Amudala