What is MongoDB?

MongoDB is a NoSQL database, meaning it doesn't use tables like traditional SQL databases. Instead, it stores data in a flexible, JSON-like format called BSON (Binary JSON). It's designed to handle large amounts of data, scale easily, and work with unstructured or semi-structured data.

Document-based

Stores data in documents (like JSON objects) instead of rows and columns.

Schema-less

You can store different types of data in the same collection without a fixed structure.

Scalable

Supports horizontal scaling (adding more servers) through sharding.

High Performance

Fast for read/write operations, especially with large datasets.

Flexible

Great for applications with changing data structures, like e-commerce or social media.

Key Concepts in MongoDB

Here's what you need to know about MongoDB for an interview:

MongoDB Data Storage Design
  1. Database: A container for collections. One MongoDB instance can have multiple databases.
  2. Collection: Similar to a table in SQL, but it holds documents. No fixed schema is required.
  3. Document: A single record in a collection, stored as a BSON object (like a JSON key-value pair).
  4. Field: A key-value pair in a document (e.g., "name": "John").
  5. _id: A unique identifier automatically added to every document (like a primary key in SQL).
  6. Sharding: Splitting large datasets across multiple servers to improve performance.
  7. Replication: Copying data to multiple servers for redundancy and high availability.
  8. Indexes: Used to make queries faster by allowing efficient searching on specific fields.
  9. Aggregation: A way to process data (like grouping, filtering, or calculating) using a pipeline.
Example Document:
{ "name": "John", "age": 25, "city": "New York" }

MongoDB vs SQL

Here's a clear comparison between MongoDB (NoSQL) and SQL (Relational Databases like MySQL, PostgreSQL):

Feature MongoDB (NoSQL) SQL (Relational)
Data Structure Stores data in flexible, JSON-like documents Stores data in structured tables with rows/columns
Schema Schema-less (dynamic, no predefined structure) Fixed schema (must define tables/columns upfront)
Scalability Horizontal scaling (add servers, sharding) Vertical scaling (add more power to a single server)
Query Language Uses JavaScript-like queries (e.g., find()) Uses SQL (e.g., SELECT, JOIN)
Joins No native joins; data is often denormalized Supports complex joins between tables
Use Case Big data, real-time apps, unstructured data Structured data, transactional apps
Performance Fast for large-scale, unstructured data Fast for structured data with complex queries
Consistency Eventual consistency in distributed setups Strong consistency (ACID transactions)

When to Use MongoDB:

  • When data is unstructured or semi-structured (e.g., logs, user profiles)
  • For applications needing high scalability (e.g., e-commerce platforms)
  • When schema changes frequently (e.g., startups building MVPs)

When to Use SQL:

  • When data is highly structured and relational (e.g., financial records)
  • For applications needing complex joins and transactions (e.g., banking systems)
  • When strong consistency is critical

📘 MongoDB Queries with Explanations

MongoDB uses a query language that's easy to understand, especially if you know JavaScript. Here's a complete cheat sheet with explanations for interviews and practice.

🟢 1. Database Queries

Show all databases:

show dbs

👉 Lists all databases available in MongoDB.

Create or switch to database:

use mydb

👉 Creates (if not exists) or switches to the database mydb.

Show current database:

db

👉 Displays the name of the database currently in use.

🟢 2. Collection Queries

Show collections in current database:

show collections

👉 Lists all collections (like tables in SQL) inside the database.

Create collection:

db.createCollection("students")

👉 Creates a new collection named students.

Drop (delete) collection:

db.students.drop()

👉 Removes the students collection completely.

🟢 3. Insert Documents

Insert one document:

db.students.insertOne({ name: "Deepak", age: 21, grade: "A" })

👉 Adds a single document (record) into students.

Insert multiple documents:

db.students.insertMany([ { name: "Tushar", age: 20, grade: "B" }, { name: "Shreeram", age: 22, grade: "A" } ])

👉 Inserts multiple records in one go.

🟢 4. Find (Read) Documents

Find all documents:

db.students.find()

👉 Retrieves all documents from the collection.

Pretty print output:

db.students.find().pretty()

👉 Displays documents in a formatted (easy-to-read) way.

Find one document:

db.students.findOne()

👉 Returns the first matching document.

Find with condition:

db.students.find({ grade: "A" })

👉 Filters and returns only students with grade A.

Projection (only select fields):

db.students.find({}, { name: 1, grade: 1, _id: 0 })

👉 Returns only name and grade fields, hides _id.

🟢 5. Query Operators

Comparison operators:

db.students.find({ age: { $gt: 20 } }) // age > 20 db.students.find({ age: { $gte: 21 } }) // age >= 21 db.students.find({ age: { $lt: 22 } }) // age < 22 db.students.find({ grade: { $in: ["A", "B"] } }) // grade in A or B

👉 Used for comparisons like greater than, less than, in.

Logical operators:

db.students.find({ $and: [ { grade: "A" }, { age: { $gt: 20 } } ] }) db.students.find({ $or: [ { grade: "A" }, { age: { $lt: 21 } } ] })

👉 Combine multiple conditions with AND / OR.

Not equal:

db.students.find({ grade: { $ne: "C" } })

👉 Returns students whose grade is not C.

🟢 6. Update Documents

Update one:

db.students.updateOne( { name: "Deepak" }, { $set: { grade: "A+" } } )

👉 Finds student with name Deepak and updates grade to A+.

Update many:

db.students.updateMany( { grade: "B" }, { $set: { grade: "B+" } } )

👉 Updates grade for all students with B → B+.

🟢 7. Delete Documents

Delete one:

db.students.deleteOne({ name: "Tushar" })

👉 Deletes the first document that matches name = Tushar.

Delete many:

db.students.deleteMany({ grade: "C" })

👉 Deletes all students whose grade is C.

🟢 8. Sorting & Limiting

Sorting:

db.students.find().sort({ age: 1 }) // ascending db.students.find().sort({ age: -1 }) // descending

👉 Sorts results by age in ascending/descending order.

Limiting results:

db.students.find().limit(2)

👉 Returns only 2 documents.

Skipping documents:

db.students.find().skip(2)

👉 Skips first 2 documents.

🟢 9. Indexes

Create index:

db.students.createIndex({ name: 1 })

👉 Creates index on name field (improves search performance).

View indexes:

db.students.getIndexes()

👉 Shows all indexes created.

🟢 10. Aggregation (Powerful Analytics)

db.students.aggregate([ { $match: { grade: "A" } }, // filter grade = A { $group: { _id: "$grade", count: { $sum: 1 } } }, // group & count { $sort: { count: -1 } } // sort by count ])

👉 Aggregation pipeline:

  1. $match → filter
  2. $group → group by grade & count
  3. $sort → order results

🟢 11. Other Useful Queries

Count documents:

db.students.countDocuments({ grade: "A" })

👉 Counts students with grade A.

Distinct values:

db.students.distinct("grade")

👉 Finds unique grade values.

Rename field:

db.students.updateMany({}, { $rename: { "grade": "classGrade" } })

👉 Renames field grade → classGrade.

Add new field to all documents:

db.students.updateMany({}, { $set: { status: "Active" } })

👉 Adds new field status to all documents.

Common MongoDB Interview Questions

1. What is MongoDB?

MongoDB is a NoSQL database that stores data in flexible, JSON-like documents called BSON. It's schema-less and great for handling large, unstructured data.

2. What are the advantages of MongoDB?

Flexible schema, easy to scale, fast for large datasets, supports geospatial queries, and works well with modern apps like web or mobile.

3. What is a document in MongoDB?

A document is a single record in a collection, stored as a JSON-like object with key-value pairs.

4. How does MongoDB ensure high availability?

Through replication, where data is copied to multiple servers (replica sets). If one server fails, another takes over.

5. What is sharding?

Sharding splits large datasets across multiple servers to improve performance and handle big data.

6. How do you handle relationships in MongoDB?

  • Embedding: Storing related data in a single document
  • Referencing: Storing related data in separate collections and linking them with IDs

7. What is an aggregation pipeline?

It's a series of stages (like $match, $group, $sort) to process and transform data, similar to SQL's GROUP BY or JOIN.

8. When would you not use MongoDB?

For highly relational data, complex joins, or applications needing strict ACID transactions (e.g., banking systems).

Tips for Interview Preparation

  • Understand CRUD: Be comfortable with Create (insert), Read (find), Update (update), and Delete (delete) operations.
  • Practice Queries: Run MongoDB queries on a local database (use MongoDB Compass or the MongoDB shell).
  • Know Indexing: Explain how indexes improve performance and their trade-offs (e.g., slower writes).
  • Explain Scalability: Talk about sharding and replication confidently.
  • Compare with SQL: Be ready to discuss when to use MongoDB vs SQL based on use cases.

Sample MongoDB Query Scenario

Question:

You have a products collection with documents like:

{ "_id": 1, "name": "Laptop", "price": 1000, "category": "Electronics" } { "_id": 2, "name": "Phone", "price": 500, "category": "Electronics" } { "_id": 3, "name": "Shirt", "price": 50, "category": "Clothing" }

Write queries to:

  1. Find all products in the "Electronics" category.
  2. Update the price of the "Laptop" to 1200.
  3. Count products with a price greater than 100.

Answers:

1. Find Electronics:

db.products.find({ "category": "Electronics" })

2. Update Laptop price:

db.products.updateOne({ "name": "Laptop" }, { $set: { "price": 1200 } })

3. Count products with price > 100:

db.products.countDocuments({ "price": { $gt: 100 } })