Basics of MongoDB
Basics of MongoDB Interview with follow-up questions
1. What is MongoDB and why is it different from traditional relational databases?
MongoDB is a document-oriented NoSQL database (currently MongoDB 8.x) that stores data as BSON (Binary JSON) documents inside collections rather than rows inside tables. Each document is a flexible set of key-value pairs, so two documents in the same collection can have different fields — there is no rigid, predefined schema to migrate when requirements change.
The main differences from a relational database:
- Data model: documents and collections instead of rows and tables. Related data is often embedded in one document rather than split across normalized tables and reassembled with JOINs (though MongoDB does support left-outer joins via
$lookupin the aggregation pipeline). - Schema: dynamic/flexible vs. fixed. You can still enforce structure with
$jsonSchemavalidation when you want it. - Scaling: built for horizontal scale-out via sharding and high availability via replica sets, where RDBMS traditionally scale vertically.
A common interviewer trap: "MongoDB has no transactions / isn't ACID." That's outdated — MongoDB has supported multi-document ACID transactions since 4.0 (replica sets) and 4.2 (sharded clusters), and single-document writes have always been atomic. The honest framing in 2026 is that MongoDB shines when your access patterns favor flexible, hierarchical data and scale-out, while a normalized RDBMS still fits highly relational, transaction-heavy domains — and the two camps have converged (SQL added JSON; MongoDB added joins and ACID).
Follow-up 1
What are some of the advantages of MongoDB over traditional databases?
Some advantages of MongoDB over traditional databases include:
- Flexible Schema: MongoDB allows for dynamic and unstructured data, making it easier to handle evolving data models.
- Scalability: MongoDB can scale horizontally by sharding data across multiple servers, providing high performance and handling large amounts of data.
- High Availability: MongoDB supports replica sets, which provide automatic failover and data redundancy, ensuring high availability.
- Fast Queries: MongoDB's query language and indexing capabilities allow for fast and efficient querying of data.
- Developer Productivity: MongoDB's JSON-like document model is familiar to developers and allows for easy integration with modern programming languages and frameworks.
Follow-up 2
Can you give an example of a scenario where MongoDB would be a better choice than a relational database?
MongoDB would be a better choice than a relational database in scenarios where:
- Flexible Schema: The data has a dynamic or evolving schema, and it would be difficult to define a fixed schema in advance.
- Unstructured Data: The data is unstructured or semi-structured, such as social media posts, sensor data, or log files.
- Scalability: The application needs to handle a large amount of data or high write/read throughput, and horizontal scaling is required.
- Real-time Analytics: The application requires real-time analytics or data processing, and the ability to perform complex queries on large datasets.
- Agile Development: The development team prefers a flexible and agile development process, where schema changes can be made easily without downtime or complex migrations.
2. Can you explain the basic components of MongoDB such as databases, collections, and documents?
MongoDB organizes data in a three-level hierarchy. The basic components are:
Database: the top-level container that holds collections. A single MongoDB server (or cluster) can host many databases, each isolated with its own files and permissions.
Collection: a grouping of documents, roughly analogous to a table in an RDBMS. Collections are schema-flexible by default — documents within one can have different fields — but you can attach
$jsonSchemavalidation rules to enforce structure when you need it. Collections are created lazily (on first insert) and can be sharded for horizontal scale.Document: a single record, stored as BSON (Binary JSON) — a binary form of JSON that adds types like
Date,ObjectId,Decimal128, and binary data. A document is a set of field-value pairs and can nest other documents and arrays. Each has an_idprimary key (an auto-generatedObjectIdif you don't supply one), and the max document size is 16 MB (use GridFS for larger payloads).
A useful follow-up framing: database → collection → document maps loosely to database → table → row, but the big difference is that a document can embed related data hierarchically, so one read often returns what would take several joins in SQL.
Follow-up 1
How does the structure of a MongoDB database differ from a SQL database?
The structure of a MongoDB database differs from a SQL database in the following ways:
Schema: In a SQL database, you define a schema before inserting data, which enforces a fixed structure for all rows in a table. In MongoDB, there is no fixed schema, and each document in a collection can have a different structure.
Relationships: In a SQL database, you can define relationships between tables using foreign keys. In MongoDB, you can embed related data within a document or use references to link documents.
Joins: In a SQL database, you can perform joins to combine data from multiple tables. In MongoDB, you can denormalize data by embedding related data within a document, reducing the need for joins.
Transactions: SQL databases support ACID transactions, which ensure data consistency. MongoDB supports multi-document transactions starting from version 4.0, but they are not as widely used as in SQL databases.
Follow-up 2
What is the significance of collections in MongoDB?
Collections in MongoDB are significant because they provide a way to organize and group related documents. They are equivalent to tables in a SQL database. Collections do not enforce a fixed schema, which means that documents within a collection can have different fields and structures. This flexibility allows for easy scalability and adaptability to changing data requirements. Collections also provide a logical separation of data, making it easier to manage and query specific sets of documents.
Follow-up 3
Can you give an example of a document in MongoDB?
Sure! Here's an example of a document in MongoDB:
{
"_id": ObjectId("5f6a2d8e4b1d9e6e2c9e7a7e"),
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
In this example, the document represents a person with fields like name, age, email, and address. The _id field is a unique identifier for the document, automatically generated by MongoDB if not provided. The address field is an embedded document, which allows for nesting of data within a document.
3. How is data stored in MongoDB?
MongoDB stores data as BSON (Binary JSON) documents grouped into collections within databases. BSON is a binary-encoded superset of JSON: it keeps the familiar field-value structure but adds types JSON lacks — ObjectId, Date, Decimal128, binary data, and 32/64-bit integers — and is designed to be fast to traverse and lightweight to scan.
Each document is self-describing and can have a different shape from its neighbors (flexible schema), so structure can evolve without a migration. Every document carries an _id primary key that is unique, immutable, and indexed.
On disk, MongoDB uses the WiredTiger storage engine (the old MMAPv1 engine was removed years ago). WiredTiger provides document-level concurrency control, compression (snappy/zlib/zstd), and MVCC snapshots — which is what underpins consistent reads and multi-document transactions. Documents are capped at 16 MB; for larger files you use GridFS, which chunks the file across documents.
A common follow-up: "Is BSON just stored JSON?" No — it's binary, typed, and length-prefixed for efficient skipping during scans, which is why MongoDB can index and query nested fields directly.
Follow-up 1
What is BSON and how does it relate to JSON?
BSON stands for Binary JSON. It is a binary representation of JSON-like documents. BSON extends the JSON format to include additional data types and features that are not natively supported in JSON. BSON is designed to be efficient in terms of storage space and serialization/deserialization performance. It is used as the primary data storage format in MongoDB. BSON documents can be easily converted to and from JSON format.
Follow-up 2
What are the advantages of the BSON format used by MongoDB?
The BSON format used by MongoDB offers several advantages over plain JSON:
Additional Data Types: BSON supports additional data types such as Date, Binary, and ObjectId, which are not natively supported in JSON. This allows for more precise representation of data.
Efficient Storage: BSON is designed to be compact and efficient in terms of storage space. It uses a binary format, which reduces the size of the data compared to plain text JSON.
Fast Serialization/Deserialization: BSON is optimized for fast serialization and deserialization. This allows for efficient data transfer between the application and the database.
Rich Querying and Indexing: BSON supports a wide range of query operators and indexing options, which enable powerful and efficient querying capabilities in MongoDB.
Overall, the BSON format enhances the performance, flexibility, and functionality of MongoDB as a document database.
4. What is the role of the _id field in MongoDB documents?
The _id field is the primary key of every MongoDB document — it uniquely identifies the document within its collection. Key properties:
- Mandatory and unique: every document must have an
_id, and it's backed by a unique index that MongoDB creates automatically on every collection. - Auto-generated if omitted: if you don't supply one on insert, MongoDB generates a 12-byte ObjectId — 4-byte timestamp + 5-byte random value + 3-byte incrementing counter. That structure makes ObjectIds roughly monotonic (sortable by creation time) and unique across machines.
- Immutable: you can't change
_idafter insert; to "change" it you delete and re-insert.
You can also supply your own _id (a string, number, UUID, or even a sub-document) — useful when you have a natural key like an email or SKU, which avoids a second unique index.
A common follow-up/gotcha: because ObjectIds embed a timestamp, sequential inserts hit the same side of the B-tree index, which can create a write hotspot at very high insert rates. For write-heavy or sharded workloads, interviewers like to hear that you'd consider a hashed shard key or a different _id strategy to spread writes.
Follow-up 1
Can you customize the _id field in MongoDB?
Yes, you can customize the _id field in MongoDB. By default, MongoDB generates a unique ObjectId value for the _id field. However, you can also use your own custom values for the _id field, as long as they are unique within the collection. For example, you can use a string, integer, or any other valid BSON type as the value for the _id field.
Follow-up 2
What happens if you don't provide an _id field in a document?
If you don't provide an _id field in a document, MongoDB will automatically generate a unique ObjectId value for the _id field when the document is inserted. This ensures that each document has a unique identifier. However, if you want to use your own custom values for the _id field, you need to explicitly provide them when inserting the document.
5. How do you create a database and a collection in MongoDB?
In MongoDB both databases and collections are created lazily — they don't physically exist until you write data into them.
To select (and implicitly create) a database in mongosh, use the use command:
use mydb
This just switches context. The database isn't persisted until it contains at least one collection with data.
A collection is created automatically the first time you insert into it:
db.mycollection.insertOne({ name: "Ada" })
You can also create one explicitly with createCollection() — useful when you need options such as schema validation, a capped collection, or time-series settings:
db.createCollection("mycollection", {
validator: { $jsonSchema: { /* ... */ } }
})
A common follow-up/gotcha: if you run use mydb and then show dbs, you won't see mydb until you've actually written a document — interviewers ask this to confirm you understand MongoDB's lazy creation. Note we use mongosh here; the legacy mongo shell was removed in MongoDB 6.0.
Follow-up 1
What happens if you try to insert a document into a non-existent collection?
If you try to insert a document into a non-existent collection, MongoDB will automatically create the collection and then insert the document. This behavior is different from traditional relational databases where you need to explicitly create a table before inserting data into it.
Follow-up 2
How can you check if a database or collection exists in MongoDB?
To check if a database exists in MongoDB, you can use the show dbs command in the MongoDB shell. This command will display a list of all the databases in the MongoDB instance.
To check if a collection exists in a specific database, you can use the show collections command followed by the name of the database. For example, to check if the 'mycollection' collection exists in the 'mydb' database, you can run the following command in the MongoDB shell:
use mydb
show collections
If the collection exists, it will be listed in the output. If the collection does not exist, the output will be empty.
6. How do you decide between embedding and referencing when designing a MongoDB schema?
The single most important MongoDB design question — interviewers want to see that you model around access patterns, not normalization. The core rule: data that is queried together should be stored together.
Embed (nest sub-documents) when:
- The relationship is one-to-one or one-to-few (e.g. a user and their addresses).
- The child data is always loaded with the parent and doesn't grow unbounded.
- You want a single atomic write (single-document operations are always atomic — no transaction needed).
Reference (store an _id and join with $lookup) when:
- The relationship is one-to-many/many-to-many or the array would grow unbounded (e.g. a blog post and its comments at scale).
- The sub-entity is large, shared across documents, or updated independently.
- You'd otherwise risk the 16MB document limit or rewriting huge arrays on every update.
// Embedded (one-to-few)
{ _id: 1, name: "Ada", addresses: [{ city: "London" }, { city: "Paris" }] }
// Referenced (one-to-many)
{ _id: 1, name: "Ada" } // users
{ _id: 99, userId: 1, text: "comment..." } // comments
Follow-ups: name the classic patterns — Extended Reference (duplicate a few hot fields to avoid a join), Subset (embed the most-recent N, reference the rest), Computed, and Bucket (for time-series/IoT). The standard gotcha: avoid unbounded arrays inside a document.
Live mock interview
Mock interview: Basics of MongoDB
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.