💼 100+ MongoDB Interview Questions
Complete Interview Preparation Guide with Detailed Answers
🎯 About This Interview Guide
This comprehensive guide contains 110+ MongoDB interview questions covering all topics from basics to advanced distributed systems. Each question includes detailed answers with examples.
- Read the question first: Try to answer mentally before checking
- Understand, don't memorize: Focus on concepts, not rote learning
- Practice verbally: Explain answers out loud
- Track progress: Use the progress bar to see completion
- Review regularly: Revisit difficult questions
Your Progress
0 / 110 questions reviewed
- Always explain your thought process
- Use examples to illustrate concepts
- Discuss trade-offs when relevant
- Ask clarifying questions
- Be honest if you don't know something
🌱 Basics (Questions 1-20)
Fundamental MongoDB concepts every developer should know.
✓ Complete Answer:
What is MongoDB?
MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents (BSON format). It's designed for scalability, flexibility, and high performance.
Key Differences from SQL:
1. Data Model
- MongoDB: Document-based (JSON-like BSON)
- SQL: Table-based (rows and columns)
// MongoDB Document
{
_id: ObjectId("..."),
name: "Alice",
age: 28,
address: {
street: "123 Main St",
city: "SF"
},
hobbies: ["reading", "coding"]
}
-- SQL Tables
users: id, name, age
addresses: id, user_id, street, city
hobbies: id, user_id, hobby
2. Schema
- MongoDB: Flexible/dynamic schema
- SQL: Fixed/rigid schema
3. Scaling
- MongoDB: Built for horizontal scaling (sharding)
- SQL: Traditionally vertical scaling
4. Query Language
- MongoDB: JSON-based queries
- SQL: Structured Query Language (SQL)
When to use MongoDB: Rapid development, flexible data models, horizontal scaling, real-time analytics
When to use SQL: Complex transactions, complex JOINs, strict data integrity requirements
✓ Complete Answer:
MongoDB Hierarchy:
MongoDB Server
├─ Database 1 (e.g., "ecommerce")
│ ├─ Collection 1 (e.g., "users")
│ │ ├─ Document 1 { _id: 1, name: "Alice", ... }
│ │ ├─ Document 2 { _id: 2, name: "Bob", ... }
│ │ └─ Document 3 { _id: 3, name: "Charlie", ... }
│ ├─ Collection 2 (e.g., "products")
│ │ ├─ Document 1 { _id: 1, name: "Laptop", ... }
│ │ └─ Document 2 { _id: 2, name: "Phone", ... }
│ └─ Collection 3 (e.g., "orders")
└─ Database 2 (e.g., "analytics")
1. Database
- Physical container for collections
- Each database has its own files on disk
- Multiple databases can exist on one server
- Example: "ecommerce", "users", "analytics"
// Create/switch to database use ecommerce // List all databases show dbs
2. Collection
- Group of MongoDB documents (like SQL table)
- Schema-less: documents can have different fields
- Created automatically when first document inserted
- Naming: lowercase, no spaces (use underscores)
// Create collection explicitly
db.createCollection("users")
// List all collections
show collections
3. Document
- Basic unit of data (like SQL row)
- Stored in BSON format (Binary JSON)
- Maximum size: 16MB per document
- Contains field-value pairs
- Every document has a unique _id field
// Example document
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: "Alice Johnson",
email: "[email protected]",
age: 28,
interests: ["coding", "music"],
address: {
street: "123 Main St",
city: "San Francisco",
zip: "94102"
},
registered: ISODate("2024-01-15T10:30:00Z")
}
SQL Comparison:
- Database = Database (same)
- Collection = Table
- Document = Row
- Field = Column
✓ Complete Answer:
BSON (Binary JSON):
BSON is a binary-encoded serialization format used by MongoDB to store documents and make remote procedure calls. It extends JSON with additional data types.
Key Differences:
| Aspect | JSON | BSON |
|---|---|---|
| Format | Text-based | Binary-encoded |
| Human Readable | Yes | No |
| Size | Larger (text) | Smaller (binary) |
| Speed | Slower to parse | Faster to parse |
| Data Types | Limited (string, number, boolean, null, array, object) | Extended (Date, ObjectId, Binary, Int32, Int64, Decimal128, etc.) |
Additional BSON Data Types:
{
_id: ObjectId("507f1f77bcf86cd799439011"), // ObjectId - unique identifier
name: "Alice", // String
age: 28, // Int32
balance: NumberDecimal("1234.56"), // Decimal128 - precise decimals
birthDate: ISODate("1995-03-15T00:00:00Z"), // Date
avatar: BinData(0, "base64string..."), // Binary data
verified: true, // Boolean
tags: ["user", "premium"], // Array
metadata: { key: "value" } // Embedded document
}
Why BSON?
- Efficiency: Binary format is faster to encode/decode
- Traversable: Can traverse documents without parsing entire structure
- Rich Types: Supports more data types than JSON
- Optimized for MongoDB: Designed specifically for database operations
✓ Complete Answer:
The _id Field:
The _id field is a unique identifier for each document in a MongoDB collection. It serves as the primary key.
Key Characteristics:
- Mandatory: YES - every document MUST have an _id field
- Unique: Must be unique within the collection
- Immutable: Cannot be changed after document creation
- Indexed: Automatically indexed for fast lookups
- Auto-generated: MongoDB creates one if not provided
ObjectId Structure:
If you don't provide an _id, MongoDB generates an ObjectId - a 12-byte BSON type:
ObjectId("507f1f77bcf86cd799439011")
|-------|--|----|--------|
| | | |
| | | └─ 3 bytes: Counter (random start)
| | └─ 2 bytes: Process ID
| └─ 2 bytes: Machine ID
└─ 4 bytes: Timestamp (seconds since Unix epoch)
Breakdown:
- Timestamp: When the document was created
- Machine ID: Unique to the machine
- Process ID: Unique to the MongoDB process
- Counter: Random value, incremented for each document
Custom _id Values:
// You can provide your own _id
db.users.insertOne({
_id: 1, // Integer
name: "Alice"
})
db.users.insertOne({
_id: "user_12345", // String
name: "Bob"
})
db.users.insertOne({
_id: {
company: "ABC",
employee: 101
}, // Embedded document
name: "Charlie"
})
// MongoDB auto-generates if not provided
db.users.insertOne({
name: "Diana"
// _id: ObjectId("...") will be added automatically
})
- Duplicate _id values cause insertion errors
- Cannot update _id after insertion
- Can use any BSON type as _id (string, number, ObjectId, etc.)
- ObjectId ensures uniqueness across distributed systems
When to use custom _id:
- When you have a natural unique identifier (email, username, SKU)
- When migrating from SQL (can use existing primary keys)
- For better readability in URLs or APIs
When to use ObjectId:
- Default choice (no natural identifier)
- Distributed systems (ensures uniqueness without coordination)
- Contains creation timestamp (useful for sorting)
✓ Complete Answer:
MongoDB is NOT truly "schemaless"
More accurate description: "Flexible schema" or "Dynamic schema"
What "Flexible Schema" Means:
- Documents in the same collection CAN have different fields
- No need to define schema before inserting data
- Can add/remove fields on the fly
- BUT: You should still design a logical schema!
// Valid in MongoDB - different structures in same collection
db.users.insertMany([
{
name: "Alice",
email: "[email protected]",
age: 28
},
{
name: "Bob",
email: "[email protected]",
phone: "555-1234", // Different field
verified: true // Another different field
},
{
username: "charlie", // Even field names can differ
contact: { // Nested structure
email: "[email protected]"
}
}
])
// All valid! MongoDB doesn't complain
But YOU SHOULD Design a Schema:
- Data that's accessed together should be stored together
- Embed when you have one-to-few relationships
- Reference when you have one-to-many or many-to-many
- Design for your query patterns, not for normalization
Schema Validation (Optional but Recommended):
MongoDB supports schema validation to enforce structure:
// Create collection with validation rules
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "age"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "must be a valid email"
},
age: {
bsonType: "int",
minimum: 18,
maximum: 150,
description: "must be an integer between 18 and 150"
}
}
}
}
})
// Now this will be rejected:
db.users.insertOne({ name: "Alice" }) // Missing email and age
// Error: Document failed validation
Advantages of Flexible Schema:
- Rapid development (no migrations for new fields)
- Easy to evolve schema over time
- Can handle heterogeneous data
- Good for prototyping and iterative development
Disadvantages if Misused:
- Can lead to inconsistent data
- Application code becomes complex (handling different structures)
- Harder to maintain without documentation
- Query performance can suffer
Treat MongoDB like it HAS a schema - design it thoughtfully, document it, and use validation rules. The flexibility is there when you need it, but don't abuse it!
✓ Complete Answer:
MongoDB BSON Data Types:
{
// String
name: "Alice Johnson",
// Numbers
age: 28, // Int32 (default for integers)
salary: NumberLong("75000"), // Int64 (large integers)
price: 19.99, // Double (default for decimals)
precise: NumberDecimal("123.456789"), // Decimal128 (financial data)
// Boolean
isActive: true,
// Date
createdAt: ISODate("2024-01-15T10:30:00Z"),
birthDate: new Date("1995-03-15"),
// ObjectId
_id: ObjectId("507f1f77bcf86cd799439011"),
userId: ObjectId("507f1f77bcf86cd799439012"),
// Array
tags: ["mongodb", "database", "nosql"],
scores: [85, 90, 92],
// Embedded Document (Object)
address: {
street: "123 Main St",
city: "San Francisco",
zip: "94102"
},
// Binary Data
avatar: BinData(0, "base64encodedstring..."),
// Null
middleName: null,
// Regular Expression
pattern: /^user_.+@example\.com$/,
// JavaScript Code
validator: Code("function() { return this.age >= 18; }"),
// Timestamp (internal MongoDB use)
lastModified: Timestamp(1638360000, 1),
// Min/Max Key (comparison purposes)
minValue: MinKey(),
maxValue: MaxKey()
}
Common Data Types:
- String: UTF-8 text
- Integer: 32-bit (Int32) or 64-bit (Int64/NumberLong)
- Double: 64-bit floating point
- Decimal128: High-precision decimal (for money)
- Boolean: true/false
- Date: Milliseconds since Unix epoch
- ObjectId: 12-byte unique identifier
- Array: List of values
- Object: Embedded document
- Null: Represents null/missing value
- Binary: Binary data
✓ Complete Answer:
Namespace: A namespace is the concatenation of the database name and collection name.
Format: database.collection Examples: - ecommerce.users - ecommerce.products - analytics.events - blog.posts - blog.comments
Why Namespaces Matter:
- Uniquely identifies a collection across databases
- Used internally by MongoDB for organization
- Appears in logs and monitoring tools
- Maximum length: 120 bytes
✓ Complete Answer:
Maximum Document Size: 16 MB
Why This Limit Exists:
- Performance: Large documents slow down reads/writes
- Memory: Documents are loaded into RAM for processing
- Network: Large documents consume bandwidth
- Design Principle: Encourages proper schema design
Use GridFS: MongoDB's specification for storing large files
// GridFS splits files into chunks (255KB each) // Stores metadata in files collection // Stores chunks in chunks collection // Example: Store a video file mongofiles put video.mp4 // GridFS handles files of any size (no 16MB limit)
Best Practices:
- Keep documents small and focused
- Use references for large related data
- Store large files (images, videos) in GridFS or cloud storage
- Store only file URLs/IDs in documents
✓ Complete Answer:
MongoDB Drivers: Libraries that allow applications to interact with MongoDB databases from different programming languages.
Official MongoDB Drivers:
- Node.js: mongodb npm package
- Python: PyMongo
- Java: MongoDB Java Driver
- C#/.NET: MongoDB.Driver
- Go: mongo-go-driver
- PHP: MongoDB PHP Library
- Ruby: Mongoid, Mongo Ruby Driver
- C++: MongoDB C++ Driver
// Node.js example
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
// Python example
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017')
// Java example
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
✓ Complete Answer:
Two ways to represent relationships in MongoDB:
1. Embedded Documents (Denormalization)
Store related data together in the same document
// User with embedded addresses
{
_id: 1,
name: "Alice",
email: "[email protected]",
addresses: [
{
type: "home",
street: "123 Main St",
city: "San Francisco",
zip: "94102"
},
{
type: "work",
street: "456 Market St",
city: "San Francisco",
zip: "94105"
}
]
}
// Single query gets everything
db.users.findOne({ _id: 1 })
Pros:
- ✓ Better read performance (one query)
- ✓ Atomicity - update in single operation
- ✓ Data locality - related data together
Cons:
- ✗ Document size grows (16MB limit)
- ✗ Data duplication
- ✗ Harder to query embedded data independently
2. References (Normalization)
Store related data in separate collections, link by reference
// Users collection
{
_id: 1,
name: "Alice",
email: "[email protected]"
}
// Addresses collection (separate)
{
_id: 101,
userId: 1, // Reference to user
type: "home",
street: "123 Main St",
city: "San Francisco"
}
// Need $lookup or multiple queries
db.users.aggregate([
{ $match: { _id: 1 } },
{ $lookup: {
from: "addresses",
localField: "_id",
foreignField: "userId",
as: "addresses"
}
}
])
Pros:
- ✓ No data duplication
- ✓ Smaller documents
- ✓ Easier to query/update independently
- ✓ Good for unbounded relationships
Cons:
- ✗ Requires $lookup or multiple queries
- ✗ Slower read performance
- ✗ No atomic updates across collections
Embed when:
- One-to-few relationship (1 user → 3 addresses)
- Data accessed together
- Child data doesn't need independent queries
Reference when:
- One-to-many (1 user → 1000 orders)
- Many-to-many relationships
- Data updated frequently
- Need to query child data independently
✓ Answer:
Both are document databases but differ in consistency models, replication, and query languages. MongoDB uses BSON with powerful aggregation pipelines, while CouchDB uses JSON with MapReduce views. MongoDB is CP (consistency + partition tolerance), CouchDB is AP (availability + partition tolerance). MongoDB has automatic sharding, CouchDB uses multi-master replication.
✓ Answer:
MongoDB Compass is the official GUI for MongoDB. It provides visual exploration of data, query building without writing code, index performance analysis, schema visualization, and real-time server statistics. It's available in Full, Readonly, and Isolated editions.
✓ Answer:
mongosh (MongoDB Shell) is the modern command-line interface for MongoDB. It replaced the old mongo shell and is built on Node.js, providing better syntax highlighting, improved autocomplete, contextual help, and support for modern JavaScript (ES6+). You can write scripts, perform CRUD operations, and administer databases through mongosh.
✓ Answer:
WiredTiger is MongoDB's default storage engine since version 3.2. Key features include document-level concurrency control (allows multiple clients to modify different documents simultaneously), compression (reduces storage), snapshots for consistent backups, and checkpoints for durability. It replaced MMAPv1 for better performance and concurrency.
✓ Answer:
A capped collection is a fixed-size collection that automatically overwrites oldest documents when it reaches maximum size. Insertion order is preserved. Use cases: logging, caching, high-throughput operations. Example: db.createCollection("logs", {capped: true, size: 100000, max: 5000}). Cannot update documents to increase size, cannot delete individual documents.
✓ Answer:
GridFS is MongoDB's specification for storing files larger than 16MB. It divides files into chunks (typically 255KB) stored in two collections: fs.files (metadata) and fs.chunks (data). Use for: large files exceeding 16MB, files larger than RAM, accessing portions of files without loading entire file. Alternative: store files in cloud storage (S3) and store URLs in MongoDB.
✓ Answer:
Advantages: Schema flexibility (no migrations), horizontal scalability (sharding), high performance for read-heavy workloads, natural data representation (documents match objects), built-in replication, better for hierarchical/nested data, faster development iterations. Good for: Rapid development, real-time analytics, content management, IoT, catalogs.
✓ Answer:
Avoid MongoDB for: Complex multi-table transactions (banking), complex JOINs across many entities, highly structured data with strict relationships, systems requiring strong ACID guarantees across operations, business intelligence with complex aggregations across normalized data, legacy systems with established SQL infrastructure. Use SQL databases instead for these scenarios.
✓ Answer:
Default MongoDB port is 27017. mongos (shard router) also uses 27017. Config servers use 27019. When running multiple MongoDB instances on same machine, use different ports (27018, 27020, etc.). Connection string format: mongodb://localhost:27017/mydb
✓ Answer:
MongoDB Atlas is the official cloud-hosted Database-as-a-Service (DBaaS) offering. Features: automated backups, monitoring, automatic scaling, multi-cloud support (AWS, Azure, GCP), built-in security, global clusters, free tier available. Eliminates operational overhead of managing MongoDB infrastructure. Suitable for production deployments without managing servers.
✏️ CRUD Operations (Questions 21-35)
Questions about Create, Read, Update, and Delete operations.
✓ Complete Answer:
1. insertOne() - Insert Single Document
db.users.insertOne({
name: "Alice",
email: "[email protected]"
})
// Returns: { acknowledged: true, insertedId: ObjectId("...") }
- Inserts exactly ONE document
- Returns insertedId
- Fails if _id already exists
2. insertMany() - Insert Multiple Documents
db.users.insertMany([
{ name: "Bob", email: "[email protected]" },
{ name: "Charlie", email: "[email protected]" }
])
// Returns: {
// acknowledged: true,
// insertedIds: { 0: ObjectId("..."), 1: ObjectId("...") }
// }
- Inserts multiple documents in one operation
- More efficient than multiple insertOne() calls
- By default, ordered: stops on first error
- Can be unordered: continues on errors
3. insert() - DEPRECATED (don't use)
⚠️ Legacy method, use insertOne() or insertMany() instead
Ordered vs Unordered Insert:
// Ordered (default) - stops on first error
db.users.insertMany([
{ _id: 1, name: "Alice" },
{ _id: 2, name: "Bob" },
{ _id: 1, name: "Charlie" } // Duplicate! Stops here
{ _id: 3, name: "Diana" } // NOT inserted
])
// Unordered - continues despite errors
db.users.insertMany([
{ _id: 1, name: "Alice" },
{ _id: 2, name: "Bob" },
{ _id: 1, name: "Charlie" }, // Error, but continues
{ _id: 3, name: "Diana" } // Still inserted
], { ordered: false })
✓ Complete Answer:
1. updateOne() - Update First Matching Document
db.users.updateOne(
{ name: "Alice" }, // Filter
{ $set: { age: 29 } } // Update operators
)
// Updates only the FIRST document that matches
// Returns: {
// acknowledged: true,
// matchedCount: 1,
// modifiedCount: 1
// }
2. updateMany() - Update All Matching Documents
db.users.updateMany(
{ age: { $lt: 18 } }, // Filter: age < 18
{ $set: { category: "minor" } }
)
// Updates ALL documents that match
// Returns: {
// acknowledged: true,
// matchedCount: 5,
// modifiedCount: 5
// }
3. replaceOne() - Replace Entire Document
// BEFORE: { _id: 1, name: "Alice", age: 28, city: "SF" }
db.users.replaceOne(
{ _id: 1 },
{ name: "Alice Updated", email: "[email protected]" }
)
// AFTER: { _id: 1, name: "Alice Updated", email: "[email protected]" }
// Note: age and city are GONE! Only _id preserved
- Replaces ENTIRE document (except _id)
- Cannot use update operators ($set, $inc, etc.)
- All old fields removed, only new fields remain
// updateOne - MODIFIES fields
db.users.updateOne(
{ _id: 1 },
{ $set: { email: "[email protected]" } }
)
// Result: { _id: 1, name: "Alice", age: 28, email: "[email protected]" }
// Old fields preserved, new field added/updated
// replaceOne - REPLACES entire document
db.users.replaceOne(
{ _id: 1 },
{ email: "[email protected]" }
)
// Result: { _id: 1, email: "[email protected]" }
// Only _id and email remain!
✓ Answer:
find(): Returns a cursor to all matching documents. Can chain methods (.limit(), .sort(), .skip()). Example: db.users.find({age: {$gt: 25}})
findOne(): Returns first matching document as object (not cursor). Cannot chain cursor methods. Returns null if no match. Example: db.users.findOne({_id: 1})
✓ Answer:
deleteOne(): Deletes first match. db.users.deleteOne({name: "Alice"})
deleteMany(): Deletes all matches. db.users.deleteMany({age: {$lt: 18}})
drop(): Deletes entire collection. db.users.drop()
All return deleteCount showing number of documents deleted.
✓ Answer:
Upsert = Update + Insert. If document exists, update it; if not, insert new document. Use {upsert: true} option. Example: db.users.updateOne({email: "[email protected]"}, {$set: {name: "Bob"}}, {upsert: true}). Useful for: preventing duplicates, ensuring data exists, atomic operations.
✓ Answer:
Projection specifies which fields to return. 1 = include, 0 = exclude. db.users.find({}, {name: 1, email: 1, _id: 0}) returns only name and email. Cannot mix inclusion/exclusion (except _id). Reduces network overhead and improves performance.
✓ Answer:
Comparison: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin
Logical: $and, $or, $not, $nor
Element: $exists, $type
Array: $all, $elemMatch, $size
Text: $regex, $text
✓ Answer:
Match exact array: {tags: ["red", "blue"]}. Match any element: {tags: "red"}. Match all: {tags: {$all: ["red", "blue"]}}. Array size: {tags: {$size: 3}}. Query array of objects: {"items.qty": {$gt: 10}}
✓ Answer:
$elemMatch matches documents where at least one array element satisfies all conditions. Example: db.users.find({scores: {$elemMatch: {$gte: 80, $lt: 90}}}) finds users with at least one score between 80-90. Without $elemMatch, conditions apply to different elements.
✓ Answer:
Dot notation accesses nested fields: db.users.find({"address.city": "NYC"}). For arrays: {"items.0.name": "Widget"} accesses first element. Update nested: {$set: {"address.zip": "10001"}}. Must use quotes around dotted field names.
✓ Answer:
$set: Updates or adds field. {$set: {age: 30}}
$unset: Removes field entirely. {$unset: {age: ""}} (value doesn't matter)
✓ Answer:
$ operator: Updates first match. db.items.updateOne({"tags": "old"}, {$set: {"tags.$": "new"}})
$[] operator: Updates all elements. {$inc: {"scores.$[]": 5}}
$[elem] filtered: Updates matching elements. {$set: {"scores.$[elem]": 100}}, {arrayFilters: [{"elem": {$gte: 90}}]}
✓ Answer:
$push: Adds element to array. {$push: {tags: "new"}}
$pull: Removes matching elements. {$pull: {tags: "old"}}
$pop: Removes first (-1) or last (1) element. {$pop: {tags: 1}}
$addToSet: Adds only if not exists (prevents duplicates). {$addToSet: {tags: "unique"}}
✓ Answer:
$inc: Increments field by value. {$inc: {age: 1, views: 5}}. Use negative for decrement.
$mul: Multiplies field by value. {$mul: {price: 1.1}} increases price by 10%.
✓ Answer:
Atomically modifies and returns a document. Use findOneAndUpdate(), findOneAndReplace(), or findOneAndDelete(). Returns document before or after modification (controlled by options). Useful for: counters, queues, locks. Example: db.counters.findOneAndUpdate({_id: "userId"}, {$inc: {seq: 1}}, {returnNewDocument: true})
🚀 Indexing (Questions 36-50)
Questions about MongoDB indexes and query optimization.
Indexes improve query performance by allowing quick document location without full collection scans. Trade-off: faster reads, slower writes. Every collection has automatic _id index.
Single Field, Compound, Multikey (arrays), Text, Geospatial (2d/2dsphere), Hashed, Wildcard, TTL.
Single: one field. Compound: multiple fields, order matters. createIndex({city: 1, age: -1})
Automatic for array fields. Each element indexed separately. Enables efficient array queries.
Full-text search support. createIndex({content: "text"}). Query: {$text: {$search: "keyword"}}
Location-based queries. 2dsphere for GeoJSON (sphere), 2d for flat. Supports $near, $geoWithin.
2d: flat plane. 2dsphere: spherical geometry (Earth), GeoJSON format, more accurate.
Indexes hash of value. Used for sharding (even distribution). Equality queries only, no ranges.
Enforces uniqueness. createIndex({email: 1}, {unique: true}). Prevents duplicates.
Only indexes docs with the field. {sparse: true}. Saves space for optional fields.
Automatically deletes docs after time. {expireAfterSeconds: 3600}. For sessions, logs.
explain("executionStats"). Look for IXSCAN (index) vs COLLSCAN (full scan).
Query execution details. Shows plan, index used, docs examined, execution time. Essential for optimization.
All returned fields in index - no document examination needed. Extremely fast. Must exclude _id if not indexed.
64 indexes maximum including _id. More indexes = slower writes.
📊 Aggregation (Questions 51-65)
MongoDB aggregation framework and pipelines.
Pipeline-based data processing framework. Transforms and analyzes data through stages. More powerful than find().
Sequence of stages processing documents. Each stage transforms data and passes to next. Example: $match → $group → $sort
Filters documents like find(). Place early in pipeline for performance. {$match: {age: {$gte: 18}}}
Groups documents by expression. Accumulates values. {$group: {_id: "$city", total: {$sum: 1}}}
Reshapes documents. Include/exclude fields, compute new fields. {$project: {name: 1, year: {$year: "$date"}}}
Left outer join with another collection. {$lookup: {from: "orders", localField: "_id", foreignField: "userId", as: "orders"}}
Deconstructs array field into separate documents. One document per array element. {$unwind: "$tags"}
$sort orders documents (1=asc, -1=desc). $limit restricts count. Always sort before limit for top-N.
$addFields adds/overwrites fields, keeps all existing. $project must explicitly include fields to keep.
Arithmetic: $add, $multiply. Array: $size, $filter. String: $concat, $substr. Date: $year, $month. Conditional: $cond, $ifNull.
Use $cond operator. {category: {$cond: {if: {$gte: ["$age", 18]}, then: "adult", else: "minor"}}}
Groups documents into buckets by value ranges. {$bucket: {groupBy: "$price", boundaries: [0, 50, 100]}}
Processes multiple aggregation pipelines in single stage. Returns multiple result sets. Good for complex analytics.
Recursive search on collection. Traverses graph/tree structures. Use for: org charts, social graphs, hierarchies.
Use find() for: simple queries, returning documents as-is. Use aggregation for: grouping, computed fields, transformations, JOINs, complex analytics.
🔁 Replication (Questions 66-80)
MongoDB replica sets and high availability.
Synchronizing data across multiple servers for redundancy and high availability. Protects against hardware failure.
Group of MongoDB instances maintaining same dataset. One primary (writes), multiple secondaries (replicate). Automatic failover.
Primary: accepts writes. Secondary: replicates data, can serve reads. Arbiter: voting only (no data), breaks election ties.
Primary fails → secondaries detect via heartbeat → election initiated → majority votes for new primary → ~12sec downtime.
Operations log. Capped collection recording all write ops. Secondaries tail oplog to replicate. Fixed size (FIFO).
Controls where reads go. Options: primary (default), primaryPreferred, secondary, secondaryPreferred, nearest.
Level of acknowledgment for writes. Controls durability. Options: w:0 (none), w:1 (primary), w:"majority" (majority nodes).
w:0: no ack (fast, risky). w:1: primary ack (default). w:"majority": majority ack (safe, slower, prevents rollback).
Write-ahead log for durability. Writes logged to journal before data files. Prevents corruption on crash. Enabled by default.
Secondaries detect primary failure → election starts → members vote → candidate with most votes and highest data wins → becomes primary.
Time delay for secondaries to catch up to primary. Caused by: network latency, slow secondary hardware, high write load.
Hidden: invisible to clients, used for backups/analytics. Delayed: lags by set time, protects against human error/corruption.
Determines election preference. Higher priority = more likely to become primary. Priority 0 = never becomes primary.
rs.status() shows member states, health, replication lag. rs.conf() shows configuration.
Undoing writes on former primary that weren't replicated. Occurs when primary rejoins after partition. Saved to rollback files.
🚀 Advanced Topics (Questions 96-100)
Advanced MongoDB features and best practices.
ACID transactions across multiple documents/collections. Since v4.0 (replica sets), v4.2 (sharded). Use sessions. Example: bank transfer between accounts.
Atomicity: single doc always atomic, multi-doc via transactions. Consistency: tunable (w concern + read pref). Isolation: snapshot. Durability: journaling + w concern.
Real-time notifications on data changes. Watch collections for insert/update/delete. Use for: notifications, cache invalidation, real-time dashboards. Requires replica set.
Official cloud DBaaS. Automated backups, monitoring, scaling. Multi-cloud (AWS/Azure/GCP). Free tier available. Eliminates operational overhead.
Create proper indexes, use projection, limit results, use aggregation for complex queries, shard when needed, monitor with explain(), proper shard key, adequate RAM, SSD storage, connection pooling.