MongoDB Fundamentals
Checking access...
MongoDB is a NoSQL document database that stores data as JSON-like documents. Unlike SQL databases with rigid schemas, MongoDB lets you store and query data with maximum flexibility.
SQL vs NoSQL
| Aspect | SQL (PostgreSQL, MySQL) | NoSQL (MongoDB) |
|---|---|---|
| Data model | Tables, rows, columns | Collections, documents |
| Schema | Fixed (defined upfront) | Flexible (per document) |
| Relationships | Foreign keys, JOINs | Embedded docs, references |
| Scaling | Vertical (bigger server) | Horizontal (sharding) |
| Query language | SQL | MongoDB Query Language |
| ACID | Full ACID | Multi-document ACID (v4.0+) |
The Document Model
A MongoDB document is a JSON-like object stored in BSON format (binary JSON):
{ "_id": ObjectId("507f1f77bcf86cd799439011"), "name": "Ada Lovelace", "email": "ada@example.com", "age": 36, "address": { "city": "London", "country": "UK" }, "hobbies": ["mathematics", "programming", "poetry"], "createdAt": ISODate("2024-01-15T10:30:00Z")}Key characteristics:
- Documents are self-contained — related data is often embedded
- Each document has a unique
_idfield (ObjectId by default) - Documents in the same collection can have different fields
- Supports nested objects and arrays natively
Installing MongoDB
Local Installation
# macOSbrew tap mongodb/brewbrew install mongodb-community@7.0brew services start mongodb-community@7.0
# Ubuntucurl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \ sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmorecho "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \ https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \ sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.listsudo apt update && sudo apt install -y mongodb-orgsudo systemctl start mongodDocker
docker run -d \ --name mongodb \ -p 27017:27017 \ -v mongodb_data:/data/db \ -e MONGO_INITDB_ROOT_USERNAME=admin \ -e MONGO_INITDB_ROOT_PASSWORD=secret \ mongo:7Verify Installation
mongosh --eval "db.version()"# Should output: 7.0.xThe Mongo Shell
mongosh is the official MongoDB shell. Connect and explore:
mongoshBasic Shell Commands
// Show all databasesshow dbs
// Switch to (or create) a databaseuse myblog
// Show current databasedb
// Show collections in current databaseshow collections
// Helphelpdb.help()Databases & Collections
Databases
A database groups related collections. Think of it like a schema in SQL:
use blog // Switch to blog database (created on first write)use ecommerce // Switch to ecommerce database
// List databasesshow dbs // Only shows databases with dataCollections
Collections are like SQL tables — they hold documents:
// Create collection explicitly (optional — created on first insert)db.createCollection("users")db.createCollection("posts")db.createCollection("comments")
// Show collectionsshow collections
// Drop a collectiondb.posts.drop()
// Drop the entire databasedb.dropDatabase()CRUD Basics
Create
// Insert one documentdb.users.insertOne({ name: "Alice", email: "alice@example.com", age: 30,})
// Insert multiple documentsdb.users.insertMany([ { name: "Bob", email: "bob@example.com", age: 25 }, { name: "Charlie", email: "charlie@example.com", age: 35 },])Read
// Find all documentsdb.users.find()
// Find with filterdb.users.find({ age: { $gt: 30 } })
// Find one documentdb.users.findOne({ email: "alice@example.com" })
// Pretty print resultsdb.users.find().pretty()
// Count documentsdb.users.countDocuments({ age: { $gte: 25 } })Update
// Update one documentdb.users.updateOne( { email: "alice@example.com" }, // filter { $set: { age: 31 } } // update)
// Update multiple documentsdb.users.updateMany( { age: { $lt: 30 } }, { $set: { status: "young" } })
// Replace entire document (except _id)db.users.replaceOne( { email: "bob@example.com" }, { name: "Bob Smith", email: "bob@example.com", age: 26, city: "NYC" })Delete
// Delete one documentdb.users.deleteOne({ email: "charlie@example.com" })
// Delete multiple documentsdb.users.deleteMany({ age: { $lt: 20 } })
// Delete all documents (but keep collection)db.users.deleteMany({})BSON Data Types
MongoDB stores data in BSON format (binary JSON). Common types:
| Type | Example | Notes |
|---|---|---|
| String | "hello" | UTF-8 |
| Number (int) | NumberInt(42) | 32-bit integer |
| Number (long) | NumberLong(10000000000) | 64-bit integer |
| Number (double) | 3.14 | Default for JS numbers |
| Boolean | true | |
| Date | ISODate("2024-01-15") | |
| ObjectId | ObjectId("...") | Auto-generated unique ID |
| Array | [1, 2, 3] | |
| Embedded document | { city: "NYC" } | Nested object |
| Null | null | |
| Regular Expression | /pattern/i |
ObjectId
Every document has an _id field. By default, it’s an ObjectId — a 12-byte value:
// ObjectId structure (12 bytes)// 4 bytes: timestamp (seconds since Unix epoch)// 5 bytes: random value (per-process)// 3 bytes: incrementing counter
// Extract timestamp from ObjectIdObjectId("507f1f77bcf86cd799439011").getTimestamp()// ISODate("2012-10-17T21:49:43Z")
// Custom _id (string)db.users.insertOne({ _id: "user_alice_001", name: "Alice"})Indexes
Indexes speed up queries at the cost of slower writes:
// Create index (ascending)db.users.createIndex({ email: 1 })
// Create compound indexdb.users.createIndex({ age: 1, name: 1 })
// List indexesdb.users.getIndexes()
// Explain query executiondb.users.find({ email: "alice@example.com" }).explain("executionStats")Import & Export Data
Export
# Export collection to JSONmongosh --quiet --eval 'db.users.find().forEach(doc => printjsononeline(doc))' > users.json
# Or use mongoexportmongoexport --db=blog --collection=users --out=users.jsonImport
# Import JSON file to collectionmongoimport --db=blog --collection=users --file=users.json --jsonArrayConnecting from Node.js
npm install mongodbconst { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";const client = new MongoClient(uri);
async function main() { try { await client.connect(); console.log("Connected to MongoDB");
const db = client.db("blog"); const users = db.collection("users");
// Insert const result = await users.insertOne({ name: "Diana", email: "diana@example.com", }); console.log("Inserted:", result.insertedId);
// Find const allUsers = await users.find().toArray(); console.log("Users:", allUsers); } finally { await client.close(); }}
main().catch(console.error);Quick Reference
// Mongo shell CRUDdb.collection.insertOne({ field: "value" })db.collection.insertMany([{ ... }, { ... }])db.collection.find({ field: "value" })db.collection.findOne({ field: "value" })db.collection.updateOne({ filter }, { $set: { field: "new" } })db.collection.updateMany({ filter }, { $set: { field: "new" } })db.collection.deleteOne({ filter })db.collection.deleteMany({ filter })
// Useful shell commandsshow dbsuse dbnameshow collectionsdb.collection.countDocuments()db.collection.getIndexes()Practice Exercises
Setup: Install MongoDB locally or via Docker. Connect with
mongoshand rundb.version().Seed a blog database: Create a
blogdatabase with apostscollection. Insert 5 posts with fields:title,content,author,tags(array),createdAt(Date),published(boolean).CRUD practice: In the
userscollection, practice each CRUD operation. Insert 3 users, find users above age 25, update one user’s email, delete a user, then view the final state.ObjectId exploration: Insert a document and inspect the generated
_id. CallgetTimestamp()on it. Try inserting a document with a custom string_id.