Skip to main content

Skillber v1.0 is here!

Learn more

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

AspectSQL (PostgreSQL, MySQL)NoSQL (MongoDB)
Data modelTables, rows, columnsCollections, documents
SchemaFixed (defined upfront)Flexible (per document)
RelationshipsForeign keys, JOINsEmbedded docs, references
ScalingVertical (bigger server)Horizontal (sharding)
Query languageSQLMongoDB Query Language
ACIDFull ACIDMulti-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 _id field (ObjectId by default)
  • Documents in the same collection can have different fields
  • Supports nested objects and arrays natively

Installing MongoDB

Local Installation

Terminal window
# macOS
brew tap mongodb/brew
brew install mongodb-community@7.0
brew services start mongodb-community@7.0
# Ubuntu
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
echo "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.list
sudo apt update && sudo apt install -y mongodb-org
sudo systemctl start mongod

Docker

Terminal window
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:7

Verify Installation

Terminal window
mongosh --eval "db.version()"
# Should output: 7.0.x

The Mongo Shell

mongosh is the official MongoDB shell. Connect and explore:

Terminal window
mongosh

Basic Shell Commands

// Show all databases
show dbs
// Switch to (or create) a database
use myblog
// Show current database
db
// Show collections in current database
show collections
// Help
help
db.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 databases
show dbs // Only shows databases with data

Collections

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 collections
show collections
// Drop a collection
db.posts.drop()
// Drop the entire database
db.dropDatabase()

CRUD Basics

Create

// Insert one document
db.users.insertOne({
name: "Alice",
email: "alice@example.com",
age: 30,
})
// Insert multiple documents
db.users.insertMany([
{ name: "Bob", email: "bob@example.com", age: 25 },
{ name: "Charlie", email: "charlie@example.com", age: 35 },
])

Read

// Find all documents
db.users.find()
// Find with filter
db.users.find({ age: { $gt: 30 } })
// Find one document
db.users.findOne({ email: "alice@example.com" })
// Pretty print results
db.users.find().pretty()
// Count documents
db.users.countDocuments({ age: { $gte: 25 } })

Update

// Update one document
db.users.updateOne(
{ email: "alice@example.com" }, // filter
{ $set: { age: 31 } } // update
)
// Update multiple documents
db.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 document
db.users.deleteOne({ email: "charlie@example.com" })
// Delete multiple documents
db.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:

TypeExampleNotes
String"hello"UTF-8
Number (int)NumberInt(42)32-bit integer
Number (long)NumberLong(10000000000)64-bit integer
Number (double)3.14Default for JS numbers
Booleantrue
DateISODate("2024-01-15")
ObjectIdObjectId("...")Auto-generated unique ID
Array[1, 2, 3]
Embedded document{ city: "NYC" }Nested object
Nullnull
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 ObjectId
ObjectId("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 index
db.users.createIndex({ age: 1, name: 1 })
// List indexes
db.users.getIndexes()
// Explain query execution
db.users.find({ email: "alice@example.com" }).explain("executionStats")

Import & Export Data

Export

Terminal window
# Export collection to JSON
mongosh --quiet --eval 'db.users.find().forEach(doc => printjsononeline(doc))' > users.json
# Or use mongoexport
mongoexport --db=blog --collection=users --out=users.json

Import

Terminal window
# Import JSON file to collection
mongoimport --db=blog --collection=users --file=users.json --jsonArray

Connecting from Node.js

Terminal window
npm install mongodb
const { 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 CRUD
db.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 commands
show dbs
use dbname
show collections
db.collection.countDocuments()
db.collection.getIndexes()

Practice Exercises

  1. Setup: Install MongoDB locally or via Docker. Connect with mongosh and run db.version().

  2. Seed a blog database: Create a blog database with a posts collection. Insert 5 posts with fields: title, content, author, tags (array), createdAt (Date), published (boolean).

  3. CRUD practice: In the users collection, 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.

  4. ObjectId exploration: Insert a document and inspect the generated _id. Call getTimestamp() on it. Try inserting a document with a custom string _id.