Section 13: Scenario Based Question

💼 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.

💡 How to Use This Guide:
  • 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
110+
Questions
All Levels
Easy to Hard
FAANG
Company Focus

Your Progress

0 / 110 questions reviewed

0%
⚠️ Interview Tips:
  • 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.

Q1 Easy Google Amazon
What is MongoDB? How is it different from traditional SQL databases?

✓ 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

Q2 Easy Microsoft
Explain the MongoDB data model. What are databases, collections, and documents?

✓ 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
Q3 Easy Amazon
What is BSON? How is it different from JSON?

✓ 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
Q4 Easy Meta
What is the _id field in MongoDB? Is it mandatory?

✓ 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
})
⚠️ Important Notes:
  • 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)
Q5 Medium Google
Explain schema design in MongoDB. Is MongoDB really "schemaless"?

✓ 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:

Best Practice: Schema Design Principles
  • 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
✓ Recommendation:

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!

Q6 Easy Meta
What are the different data types available in MongoDB?

✓ 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
Q7 Easy Amazon
What is a namespace in MongoDB?

✓ 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
Q8 Medium Google
What is the maximum document size in MongoDB? Why is there a limit?

✓ 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
⚠️ What If You Need More Than 16MB?

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
Q9 Easy Microsoft
What are MongoDB drivers? Name a few.

✓ 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");
Q10 Medium Netflix
Explain the concept of embedded documents vs references in MongoDB.

✓ 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
✓ Decision Guide:

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
Q11 Medium Amazon
What is the difference between MongoDB and CouchDB?

✓ 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.

Q12 Easy Microsoft
What is MongoDB Compass?

✓ 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.

Q13 Easy Google
What is mongosh?

✓ 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.

Q14 Medium Netflix
What is WiredTiger storage engine?

✓ 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.

Q15 Easy Meta
What is a capped collection?

✓ 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.

Q16 Medium Amazon
What is GridFS? When would you use it?

✓ 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.

Q17 Easy Google
What are the advantages of MongoDB over RDBMS?

✓ 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.

Q18 Medium Uber
When should you NOT use MongoDB?

✓ 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.

Q19 Easy Microsoft
What is the default port for MongoDB?

✓ 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

Q20 Medium Netflix
What is MongoDB Atlas?

✓ 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.

Q21 Easy Amazon
What's the difference between insertOne(), insertMany(), and insert()?

✓ 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 })
Q22 Medium Google
Explain the difference between updateOne(), updateMany(), and replaceOne().

✓ 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
⚠️ Critical Difference:
// 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!
Q23 Easy Amazon
What's the difference between find() and findOne()?

✓ 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})

Q24 Easy Google
How do you delete documents in MongoDB?

✓ 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.

Q25 Medium Meta
What is upsert? When would you use it?

✓ 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.

Q26 Easy Microsoft
Explain projection in MongoDB queries.

✓ 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.

Q27 Medium Amazon
What are query operators? Name important ones.

✓ 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

Q28 Medium Netflix
How do you query arrays in MongoDB?

✓ 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}}

Q29 Medium Google
What is $elemMatch?

✓ 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.

Q30 Easy Meta
Explain dot notation for nested documents.

✓ 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.

Q31 Easy Amazon
What is the difference between $set and $unset?

✓ Answer:

$set: Updates or adds field. {$set: {age: 30}}

$unset: Removes field entirely. {$unset: {age: ""}} (value doesn't matter)

Q32 Hard Google
How do you update array elements?

✓ 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}}]}

Q33 Medium Netflix
What are $push, $pull, $pop, and $addToSet?

✓ 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"}}

Q34 Easy Microsoft
Explain the $inc and $mul operators.

✓ 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%.

Q35 Medium Amazon
What is findAndModify()?

✓ 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.

Q36EasyGoogle
What is an index? Why are indexes important?

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.

Q37MediumAmazon
What types of indexes does MongoDB support?

Single Field, Compound, Multikey (arrays), Text, Geospatial (2d/2dsphere), Hashed, Wildcard, TTL.

Q38MediumMeta
Explain single vs compound index.

Single: one field. Compound: multiple fields, order matters. createIndex({city: 1, age: -1})

Q39MediumNetflix
What is a multikey index?

Automatic for array fields. Each element indexed separately. Enables efficient array queries.

Q40MediumGoogle
What is a text index?

Full-text search support. createIndex({content: "text"}). Query: {$text: {$search: "keyword"}}

Q41HardUber
What is a geospatial index?

Location-based queries. 2dsphere for GeoJSON (sphere), 2d for flat. Supports $near, $geoWithin.

Q42HardUber
2d vs 2dsphere indexes?

2d: flat plane. 2dsphere: spherical geometry (Earth), GeoJSON format, more accurate.

Q43MediumAmazon
What is a hashed index?

Indexes hash of value. Used for sharding (even distribution). Equality queries only, no ranges.

Q44EasyMicrosoft
What is a unique index?

Enforces uniqueness. createIndex({email: 1}, {unique: true}). Prevents duplicates.

Q45MediumGoogle
What is a sparse index?

Only indexes docs with the field. {sparse: true}. Saves space for optional fields.

Q46MediumNetflix
What is a TTL index?

Automatically deletes docs after time. {expireAfterSeconds: 3600}. For sessions, logs.

Q47MediumAmazon
How to check if index is used?

explain("executionStats"). Look for IXSCAN (index) vs COLLSCAN (full scan).

Q48MediumGoogle
What is explain() method?

Query execution details. Shows plan, index used, docs examined, execution time. Essential for optimization.

Q49HardMeta
What are covered queries?

All returned fields in index - no document examination needed. Extremely fast. Must exclude _id if not indexed.

Q50EasyMicrosoft
Max indexes per collection?

64 indexes maximum including _id. More indexes = slower writes.

📊 Aggregation (Questions 51-65)

MongoDB aggregation framework and pipelines.

Q51MediumAmazon
What is the aggregation framework?

Pipeline-based data processing framework. Transforms and analyzes data through stages. More powerful than find().

Q52MediumGoogle
What is an aggregation pipeline?

Sequence of stages processing documents. Each stage transforms data and passes to next. Example: $match → $group → $sort

Q53EasyMicrosoft
Explain $match stage.

Filters documents like find(). Place early in pipeline for performance. {$match: {age: {$gte: 18}}}

Q54MediumAmazon
Explain $group stage.

Groups documents by expression. Accumulates values. {$group: {_id: "$city", total: {$sum: 1}}}

Q55EasyMeta
What is $project for?

Reshapes documents. Include/exclude fields, compute new fields. {$project: {name: 1, year: {$year: "$date"}}}

Q56HardGoogle
Explain $lookup (MongoDB JOIN).

Left outer join with another collection. {$lookup: {from: "orders", localField: "_id", foreignField: "userId", as: "orders"}}

Q57MediumNetflix
What is $unwind?

Deconstructs array field into separate documents. One document per array element. {$unwind: "$tags"}

Q58EasyAmazon
Explain $sort and $limit.

$sort orders documents (1=asc, -1=desc). $limit restricts count. Always sort before limit for top-N.

Q59MediumGoogle
$addFields vs $project?

$addFields adds/overwrites fields, keeps all existing. $project must explicitly include fields to keep.

Q60MediumMeta
What aggregation operators are available?

Arithmetic: $add, $multiply. Array: $size, $filter. String: $concat, $substr. Date: $year, $month. Conditional: $cond, $ifNull.

Q61HardAmazon
How to do conditional aggregation?

Use $cond operator. {category: {$cond: {if: {$gte: ["$age", 18]}, then: "adult", else: "minor"}}}

Q62MediumNetflix
What is $bucket for?

Groups documents into buckets by value ranges. {$bucket: {groupBy: "$price", boundaries: [0, 50, 100]}}

Q63HardGoogle
Explain $facet stage.

Processes multiple aggregation pipelines in single stage. Returns multiple result sets. Good for complex analytics.

Q64HardMeta
What is $graphLookup?

Recursive search on collection. Traverses graph/tree structures. Use for: org charts, social graphs, hierarchies.

Q65MediumAmazon
When to use aggregation vs find()?

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.

Q66EasyGoogle
What is replication in MongoDB?

Synchronizing data across multiple servers for redundancy and high availability. Protects against hardware failure.

Q67MediumAmazon
What is a replica set?

Group of MongoDB instances maintaining same dataset. One primary (writes), multiple secondaries (replicate). Automatic failover.

Q68MediumMeta
Explain primary, secondary, arbiter nodes.

Primary: accepts writes. Secondary: replicates data, can serve reads. Arbiter: voting only (no data), breaks election ties.

Q69HardGoogle
How does automatic failover work?

Primary fails → secondaries detect via heartbeat → election initiated → majority votes for new primary → ~12sec downtime.

Q70MediumNetflix
What is the oplog?

Operations log. Capped collection recording all write ops. Secondaries tail oplog to replicate. Fixed size (FIFO).

Q71MediumAmazon
What is read preference?

Controls where reads go. Options: primary (default), primaryPreferred, secondary, secondaryPreferred, nearest.

Q72MediumGoogle
What is write concern?

Level of acknowledgment for writes. Controls durability. Options: w:0 (none), w:1 (primary), w:"majority" (majority nodes).

Q73HardMeta
Explain w:1, w:majority, w:0.

w:0: no ack (fast, risky). w:1: primary ack (default). w:"majority": majority ack (safe, slower, prevents rollback).

Q74MediumNetflix
What is journaling?

Write-ahead log for durability. Writes logged to journal before data files. Prevents corruption on crash. Enabled by default.

Q75HardGoogle
What happens during primary election?

Secondaries detect primary failure → election starts → members vote → candidate with most votes and highest data wins → becomes primary.

Q76MediumAmazon
What is replication lag?

Time delay for secondaries to catch up to primary. Caused by: network latency, slow secondary hardware, high write load.

Q77HardNetflix
What are hidden and delayed secondaries?

Hidden: invisible to clients, used for backups/analytics. Delayed: lags by set time, protects against human error/corruption.

Q78MediumGoogle
What is priority in replica sets?

Determines election preference. Higher priority = more likely to become primary. Priority 0 = never becomes primary.

Q79EasyMicrosoft
How to check replica set status?

rs.status() shows member states, health, replication lag. rs.conf() shows configuration.

Q80HardMeta
What is rollback in MongoDB?

Undoing writes on former primary that weren't replicated. Occurs when primary rejoins after partition. Saved to rollback files.

⚡ Sharding (Questions 81-95)

MongoDB horizontal scaling and distributed architecture.

Q81MediumGoogle
What is sharding in MongoDB?

Horizontal scaling by distributing data across multiple machines. Each shard holds subset of data.

Q82MediumAmazon
Why do we need sharding?

Dataset too large for single server. Vertical scaling limits reached. Need more write throughput than one primary provides.

Q83HardMeta
Components of sharded cluster?

Shards (replica sets with data), mongos (query routers), config servers (metadata storage). Minimum 2 shards, 3 config servers.

Q84HardGoogle
What is a shard key?

Field determining data distribution across shards. Immutable after sharding. Critical for performance. Must exist in every document.

Q85HardNetflix
How to choose good shard key?

High cardinality (many unique values), even distribution (no hotspots), query isolation (appears in queries). Avoid: monotonic (_id), low cardinality.

Q86MediumAmazon
What is chunk in sharding?

Contiguous range of shard key values. Default 128MB. Auto-splits when exceeds size. Balancer migrates chunks between shards.

Q87MediumGoogle
What is the balancer?

Background process distributing chunks evenly across shards. Runs on primary config server. Can schedule for off-peak hours.

Q88MediumMeta
What is mongos?

Query router. Stateless. Routes queries to correct shards, merges results. Applications connect to mongos, not shards directly.

Q89MediumNetflix
What are config servers?

Store cluster metadata (chunk ranges, shard locations). Must be replica set (3 members minimum). Critical for cluster operation.

Q90HardGoogle
Hashed vs ranged sharding?

Ranged: consecutive values on same shard (good for range queries). Hashed: even distribution (prevents hotspots, equality queries only).

Q91MediumAmazon
What is broadcast operation?

Query sent to ALL shards (no shard key in query). Slow. mongos merges results. Avoid in production.

Q92MediumMeta
What is targeted query?

Query routed to specific shard(s) using shard key. Fast. Best case: single shard. Always include shard key in queries.

Q93MediumNetflix
Can you change shard key?

NO (before 4.2). YES (4.2+) but complex: refineCollectionShardKey() or resharding. Choose carefully initially!

Q94HardGoogle
What is zone sharding?

Tags shards with zones, associates shard key ranges with zones. Use for: geography (EU data in EU), hardware tiers (SSD vs HDD).

Q95HardAmazon
Limitations of sharding?

Operational complexity, shard key immutability, broadcast queries slow, aggregation complexity, can't shard capped collections, transactions slower.

🚀 Advanced Topics (Questions 96-100)

Advanced MongoDB features and best practices.

Q96HardGoogle
What are MongoDB transactions?

ACID transactions across multiple documents/collections. Since v4.0 (replica sets), v4.2 (sharded). Use sessions. Example: bank transfer between accounts.

Q97HardMeta
Explain ACID in MongoDB.

Atomicity: single doc always atomic, multi-doc via transactions. Consistency: tunable (w concern + read pref). Isolation: snapshot. Durability: journaling + w concern.

Q98HardNetflix
What is change streams?

Real-time notifications on data changes. Watch collections for insert/update/delete. Use for: notifications, cache invalidation, real-time dashboards. Requires replica set.

Q99EasyAmazon
What is MongoDB Atlas?

Official cloud DBaaS. Automated backups, monitoring, scaling. Multi-cloud (AWS/Azure/GCP). Free tier available. Eliminates operational overhead.

Q100HardGoogle
MongoDB performance best practices?

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.