MongoDB Interview Questions

πŸ‘‹ Introduction

MongoDB is a high-performance, NoSQL, document-oriented database used for building modern, scalable applications. Unlike traditional relational databases, it stores data in flexible, JSON-like documents, enabling dynamic schemas and rapid development.

πŸš€ Features

πŸ“Š MongoDB vs SQL Databases

MongoDB is a NoSQL, document-based database that stores data in BSON format, offering schema flexibility and horizontal scaling through sharding. SQL databases are relational, table-based systems with a fixed schema, strong ACID compliance, and support for complex joins. MongoDB is great for unstructured or rapidly changing data, while SQL is ideal for structured data and systems requiring strict relational integrity.

Aspect MongoDB SQL Databases
Data Model Stores data as documents in BSON format (JSON-like), allowing nested fields and arrays. Stores data in tables with rows and columns; relationships are represented via keys.
Schema Flexible schema β€” each document in a collection can have different fields. Fixed schema β€” structure must be defined before inserting data.
Joins Does not support traditional joins; uses $lookup for simple joins or embeds related data inside documents. Supports complex joins across multiple tables using SQL.
Transactions Supports multi-document ACID transactions since MongoDB 4.0 (replica sets) and 4.2 (sharded clusters). Fully supports ACID transactions across multiple tables by default.
Scalability Designed for horizontal scaling using sharding across multiple servers. Traditionally vertically scalable; horizontal scaling requires complex configurations.
Query Language Uses MongoDB Query Language (MQL), which is JSON-like and supports rich operators. Uses SQL (Structured Query Language), standardized across relational databases.
Performance Faster for large-scale unstructured or semi-structured data due to schema flexibility and indexing. Optimized for structured data and complex queries with strong consistency guarantees.
Use Cases Real-time analytics, content management, IoT, catalogs, big data applications. Banking, ERP systems, CRM, applications requiring strict consistency and complex transactions.

πŸ›  Architecture

MongoDB follows a client–server architecture where applications interact with the database server using official drivers or APIs. Its architecture is designed for scalability, flexibility, and high availability.

πŸ“¦ CRUD Operations

MongoDB supports standard CRUD operations β€” Create, Read, Update, and Delete β€” using its rich query language. Below are basic examples using the mongo shell:

πŸ†• Create

db.users.insertOne({ name: "Alice", age: 25 });
db.users.insertMany([
    { name: "Bob", age: 30 },
    { name: "Charlie", age: 28 }
]);
    

πŸ” Read

db.users.find(); // Find all documents
db.users.find({ age: { $gt: 20 } }); // Find users with age > 20
db.users.findOne({ name: "Alice" }); // Find a single document
    

✏️ Update

db.users.updateOne(
    { name: "Alice" },
    { $set: { age: 26 } }
);
db.users.updateMany(
    { age: { $lt: 30 } },
    { $inc: { age: 1 } }
);
    

πŸ—‘ Delete

db.users.deleteOne({ name: "Alice" });
db.users.deleteMany({ age: { $lt: 25 } });
    

πŸ“Š Indexes

Indexes in MongoDB improve query performance by allowing the database to quickly locate documents without scanning every document in a collection. However, they require additional storage and can slightly impact write performance.

πŸ”Ή Creating an Index

db.users.createIndex({ age: 1 }); // Ascending order index on 'age'
db.users.createIndex({ name: -1 }); // Descending order index on 'name'
    

πŸ”Ή Viewing Indexes

db.users.getIndexes();
    

πŸ”Ή Types of Indexes

πŸ”Ή Dropping an Index

db.users.dropIndex({ age: 1 });
    

πŸ”„ Aggregation Framework

The Aggregation Framework in MongoDB is used for advanced data processing, transformation, and computation directly within the database. It works as a pipeline, where documents pass through multiple stages, each transforming them before passing them to the next stage.

πŸ“Œ Example – Calculate Total Order Amount per Customer

db.orders.aggregate([
    { $match: { status: "A" } }, // Filter orders with status 'A'
    { $group: { _id: "$cust_id", total: { $sum: "$amount" } } } // Group by customer and sum 'amount'
]);
    

πŸ”Ή Common Aggregation Stages

πŸ“Œ Example – Join Orders with Customers

db.orders.aggregate([
    { $match: { status: "A" } },
    { $lookup: {
        from: "customers",
        localField: "cust_id",
        foreignField: "_id",
        as: "customer_details"
    }},
    { $unwind: "$customer_details" },
    { $project: { _id: 0, cust_id: 1, amount: 1, "customer_details.name": 1 } }
]);
    

πŸ—„ Replication

Replication in MongoDB ensures high availability and data redundancy by synchronizing data across multiple servers. It protects against hardware failures and allows seamless recovery.

πŸ“Œ Example – Creating a Replica Set

mongod --replSet "rs0" --port 27017 --dbpath /data/db1
mongod --replSet "rs0" --port 27018 --dbpath /data/db2
mongod --replSet "rs0" --port 27019 --dbpath /data/db3

// Connect to Mongo shell and initiate:
rs.initiate({
    _id: "rs0",
    members: [
        { _id: 0, host: "localhost:27017" },
        { _id: 1, host: "localhost:27018" },
        { _id: 2, host: "localhost:27019" }
    ]
});
    

πŸ“‘ Sharding

Sharding is MongoDB’s method for horizontal scaling, where data is distributed across multiple servers (shards). This allows handling of large datasets and high-throughput operations by spreading the load.

πŸ”Ή Key Concepts

πŸ“Œ Example – Enabling Sharding

sh.enableSharding("myDatabase"); // Enable sharding for the database
sh.shardCollection(
    "myDatabase.users",
    { user_id: 1 } // Sharding key
);
    

⚑ Benefits

⚠️ Considerations

πŸ’³ Transactions

MongoDB supports multi-document ACID transactions starting from version 4.0 for replica sets and from version 4.2 for sharded clusters. Transactions allow multiple read and write operations across one or more collections to be executed atomically.

A transaction is a sequence of one or more operations (CRUD) that are executed as a single unit of work

πŸ”Ή Key Properties

πŸ“Œ Example – Multi-Document Transaction in JavaScript

const session = db.getMongo().startSession();
session.startTransaction();

try {
    const usersColl = session.getDatabase("shop").users;
    const ordersColl = session.getDatabase("shop").orders;

    usersColl.updateOne(
        { _id: 1 },
        { $inc: { balance: -50 } }
    );

    ordersColl.insertOne({
        user_id: 1,
        product: "Laptop",
        price: 50
    });

    session.commitTransaction();
} catch (error) {
    session.abortTransaction();
} finally {
    session.endSession();
}
    

⚠️ Considerations

πŸ“ Schema Design

MongoDB uses a flexible schema, allowing documents in the same collection to have different fields. Designing the schema carefully impacts performance, scalability, and maintainability.

πŸ”Ή Best Practices

βš–οΈ Embed vs Reference Decision

⚑ Performance Optimization

Performance tuning in MongoDB involves optimizing data access patterns, queries, and storage to handle high loads efficiently.

πŸ”’ Security

Securing a MongoDB deployment involves authentication, authorization, and encryption to protect data from unauthorized access.

πŸš€ Why Choose MongoDB?