MongoDB Interview Questions for Freshers: 20 Answers Tested on MongoDB 9.0
20 MongoDB interview questions for freshers with answers you can say aloud, each query run on a real MongoDB 9.0.8 server: documents and ObjectId, the 16 MiB limit, update operators, indexes and the ESR rule with explain() numbers, the aggregation pipeline, replica sets, write concern, transactions, sharding and what changed in 9.0.

The MongoDB questions freshers get asked fall into five groups: what a document database is, how documents and the _id field work, how to query and update, how indexes and the aggregation pipeline work, and how replica sets, write concern and transactions keep data safe. Below are 20 of these questions. Every answer is short enough to say aloud in an interview, and every query was run on a real MongoDB 9.0.8 server so you can see the actual output.
In short
- MongoDB 9.0 became generally available on 28 Sep 2026; the latest patch is 9.0.8 (10 Nov 2026). Atlas's free tier still runs MongoDB 8.0 with 0.5 GB of storage (MongoDB release notes and Atlas docs, accessed 23 Nov 2026).
- Limits interviewers like to ask about: 16 MiB per document (16,777,216 bytes), 100 levels of nesting, 64 indexes per collection, 50 members and 7 voting members per replica set (MongoDB Limits page).
- Skill-Lync worked example on 100,000 synthetic orders: without an index, a lookup by customer read all 100,000 documents to return 20. With an index it read 20 index keys and 20 documents.
- The same test shows the ESR rule at work. Ordering a compound index equality-sort-range read 12 index keys and needed no sort. Ordering it equality-range-sort read 2,090 keys and sorted in memory.
- New in 9.0 and worth knowing: a per-operation memory limit (default: the larger of 1 GB or 20% of server memory), a default cap of 10,000 concurrent multi-document transactions, and server-side JavaScript re-enabled on a WebAssembly engine.
How we tested these answers. We ran MongoDB 9.0.8 in Docker as a single-node replica set, because transactions need one. We loaded a deterministic synthetic e-commerce dataset: 5,000 customers and 100,000 orders, with no real people. An e-commerce database is also the most common MongoDB project in Skill-Lync's public project index: all 7 project titles that mention MongoDB (index read 23 Nov 2026) are e-commerce databases. The script and its raw output are kept with this article, so every number below can be reproduced.
Basics: what MongoDB is and how it stores data
1. What is MongoDB?
MongoDB is a document database. It stores data as flexible JSON-like documents grouped into collections, instead of rows in fixed tables. Documents in one collection can have different fields, and related data can be nested inside a document. The server is written mainly in C++. The current major version is 9.0, released on 28 Sep 2026.
A good interview answer adds the licence, because the old "MongoDB is open source" line is out of date. Since 16 Oct 2018, MongoDB Community Server has been released under the Server Side Public License (SSPL). It is free to download and use. However, the Open Source Initiative does not accept SSPL as an open-source licence.
2. How is MongoDB different from MySQL?
MySQL is a relational database: data lives in tables with a fixed schema, and you combine tables with SQL joins. MongoDB stores self-contained documents with a flexible schema, so data that is read together is usually stored together. Both support indexes, transactions and replication; the difference is the data model and how you query it.
| SQL term (MySQL) | MongoDB term |
|---|---|
| database | database |
| table | collection |
| row | document (BSON) |
| column | field |
| primary key | _id field, added automatically if you leave it out |
| JOIN | $lookup in an aggregation pipeline, or embedding |
| GROUP BY with SUM() | $group with $sum |
| multi-statement transaction | multi-document (distributed) transaction |
If you are also preparing SQL, our core SQL interview questions cover the relational side.
3. What is BSON, and why doesn't MongoDB just store JSON?
BSON is the binary format MongoDB uses to store documents and send them over the network. It is like JSON, but it has types JSON lacks, such as Date, ObjectId, binary data, 32-bit and 64-bit integers, and Decimal128 for exact money values. The binary layout is also faster to scan and parse than text.
Interviewers often follow up with "how do you store a price?". Use Decimal128 or store integer paise. Avoid a double, which cannot represent most decimal fractions exactly.
4. What is the _id field, and what is inside an ObjectId?
Every document needs a unique _id, which acts as its primary key and is always indexed. If you don't supply one, the driver adds an ObjectId. An ObjectId is 12 bytes: a 4-byte timestamp in seconds since the Unix epoch, a 5-byte random value generated once per client process, and a 3-byte counter.
getTimestamp() confirmed on MongoDB 9.0.8.Worked example. In ObjectId("6b03b338a1b2c3d4e5000001"), the first 8 hex digits, 0x6b03b338, equal 1,795,404,600 seconds. That is 23 Nov 2026, 03:30 UTC, or 09:00 IST. So you can tell roughly when a document was created without storing a separate date. A follow-up question is whether ObjectIds are strictly increasing. They are not guaranteed to be: two processes in the same second have different random parts.
5. What is the maximum size of a MongoDB document?
16 MiB, which is 16,777,216 bytes, including field names. Documents can also nest at most 100 levels deep. For anything bigger, such as videos or large PDFs, use GridFS, which splits a file into chunks, or keep the file in object storage and store only its URL in MongoDB.
Worked example. On our test server, inserting a 15 MiB document worked. Inserting a 16 MiB + 1 KiB document failed with "object to insert too large. size in bytes: 16778282, max size: 16777216".
6. Should you embed related data or reference it?
Embed when the related data is read with its parent and stays small and bounded, like an order's line items. Reference, which means storing the other document's _id, when the related data grows without limit, is shared by many documents, or is often read on its own. MongoDB's documentation lists unbounded arrays as a design anti-pattern.
Worked example. A blog post with embedded comments: we measured one comment (user name, 150 characters of text, a date) at 203.89 bytes in BSON. So one post document can hold about 82,285 such comments before it hits 16 MiB. A popular post can pass that. Long before the hard limit, every read of the post also drags all of its comments along. Put comments in their own collection with a postId field and an index on it.
Queries and updates
7. How do update operators like $set, $inc and $push work, and what is an upsert?
Update operators change parts of a document instead of replacing it. $set sets a field, $inc adds to a number, $push appends to an array and $unset removes a field. An upsert ({upsert: true}) updates the matching document, or inserts a new one if nothing matches.
db.inventory.updateOne(
{ _id: "SKU-7" },
{ $inc: { stock: -3 },
$push: { tags: "sale" },
$set: { onSale: true } }
)
// before: { _id: "SKU-7", stock: 10, tags: ["new"] }
// after: { _id: "SKU-7", stock: 7, tags: ["new", "sale"],
// onSale: true }
db.inventory.updateOne(
{ _id: "SKU-8" },
{ $setOnInsert: { stock: 0 }, $set: { tags: ["restock"] } },
{ upsert: true }
)
// matchedCount: 0, upsertedCount: 1
// -> { _id: "SKU-8", stock: 0, tags: ["restock"] }
$setOnInsert only applies when the upsert inserts. It is how you give a new document default values without overwriting an existing one.
8. What is the difference between a dotted array query and $elemMatch?
A query like {"items.sku": "SKU-1", "items.qty": 5} matches if any array element has that sku and any element, possibly a different one, has that qty. $elemMatch requires one single element to meet all the conditions. Freshers get this wrong often, so it is a favourite trick question.
// cart A: items [{sku:"SKU-1", qty:1}, {sku:"SKU-2", qty:5}]
// cart B: items [{sku:"SKU-1", qty:5}]
db.carts.find({ "items.sku": "SKU-1", "items.qty": 5 })
// returns A and B
db.carts.find({ items: { $elemMatch: { sku: "SKU-1", qty: 5 } } })
// returns only B
Indexes
9. What is an index, and how do you prove a query uses one?
An index is a sorted structure (a B-tree) on one or more fields that lets MongoDB jump straight to matching documents instead of reading the whole collection. To prove it is used, run explain("executionStats"). Look for an IXSCAN stage rather than COLLSCAN, and compare totalDocsExamined with nReturned.
db.orders.find({ customerId: 1234 }).explain("executionStats")
// no index: COLLSCAN, totalDocsExamined 100,000, nReturned 20
db.orders.createIndex({ customerId: 1 })
// with index: IXSCAN + FETCH, totalKeysExamined 20,
// totalDocsExamined 20, nReturned 20
The index cut the documents read by 5,000 times for this query. The price is paid on writes: every insert or update must also update each index, and indexes use memory. That is why you index for the queries you actually run, not every field.
explain("executionStats") on MongoDB 9.0.8, 100,000 synthetic orders.10. What is a compound index, and what is the ESR rule?
A compound index covers several fields in a set order, and the order matters. MongoDB's ESR guideline says to put fields you match exactly (Equality) first, then fields you Sort on, then fields you filter by a Range. Following it usually lets one index both filter and return results in sorted order without an in-memory sort.
Worked example. The query is "the 10 newest shipped orders worth ₹9,000 or more": find({status: "shipped", amount: {$gte: 9000}}).sort({createdAt: -1}).limit(10). That is equality on status, range on amount and a sort on createdAt. 2,090 of the 19,956 shipped orders match.
| Index | Keys examined | Docs examined | In-memory sort? |
|---|---|---|---|
| {status, amount, createdAt} (E-R-S) | 2,090 | 10 | Yes |
| {status, createdAt, amount} (E-S-R) | 12 | 10 | No |
With ESR, MongoDB walks the shipped orders newest-first, checks the amount in the index and stops after 10 matches. MongoDB's guide adds the exception: if the range filter is very selective, putting it before the sort can be faster. Measure both with explain().
11. How many indexes can a collection have?
A single collection can have at most 64 indexes, including the automatic one on _id. In practice you hit write-speed and memory costs long before that, so a good answer adds that you remove unused indexes. $indexStats shows how often each one is used.
Aggregation
12. What is the aggregation pipeline?
The aggregation pipeline is MongoDB's way of transforming and summarising data. Documents flow through a list of stages, and each stage's output feeds the next: $match filters, $group summarises, $sort orders, $project reshapes and $lookup joins. Putting $match first lets the pipeline use indexes and shrinks the data early.
db.orders.aggregate([
{ $match: { status: "delivered",
createdAt: { $gte: ISODate("2026-07-01"),
$lt: ISODate("2026-10-01") } } },
{ $lookup: { from: "customers", localField: "customerId",
foreignField: "_id", as: "c" } },
{ $unwind: "$c" },
{ $group: { _id: "$c.city", revenue: { $sum: "$amount" },
orders: { $sum: 1 } } },
{ $sort: { revenue: -1 } },
{ $limit: 3 }
])
// { _id: "Kolkata", revenue: 12333612, orders: 2401 }
// { _id: "Pune", revenue: 12002499, orders: 2364 }
// { _id: "Bengaluru", revenue: 11932016, orders: 2313 }
This is the SQL query SELECT city, SUM(amount) ... JOIN ... GROUP BY city ORDER BY 2 DESC LIMIT 3, written as stages. Being able to translate between the two is a strong signal in an interview.
13. How do you join collections in MongoDB?
Use the $lookup stage. It performs a left outer join to another collection in the same database and adds the matches as an array field on each document. Follow it with $unwind if you want one document per match. If you need a join on every read, that often means the data should be embedded instead.
14. What happens when an aggregation needs a lot of memory?
Each pipeline stage is limited to 100 MB of memory. Since MongoDB 6.0, stages that need more spill to temporary files on disk by default (the allowDiskUseByDefault parameter). MongoDB 9.0 adds a limit for the whole operation: by default the larger of 1 GB or 20% of server memory. Before 9.0, an operation could use unbounded memory.
On a 16 GB server that per-operation limit is 3.2 GB; on a 4 GB server it is the 1 GB floor. If you hit it, filter earlier with $match, project away unneeded fields, or add an index that supports the sort.
Replication, write safety and transactions
15. What is a replica set?
A replica set is a group of mongod servers holding the same data. One primary takes all writes; secondaries copy its operation log (oplog) and can take over if the primary fails, through an automatic election. MongoDB recommends at least three data-bearing members. A set can have up to 50 members, but only 7 can vote.
Worked example. An election and a "majority" write both need more than half of the voting members. That is 1 + floor(n/2): 2 of 3, 3 of 5, 4 of 7. So a 3-member set keeps accepting majority writes with one member down, and a 5-member set with two down.
16. What is write concern, and what is the default?
Write concern says how many members must acknowledge a write before MongoDB reports success. w: 1 waits for the primary only. w: "majority" waits for a majority of voting, data-bearing members, so the write survives a failover. The implicit default is w: "majority", and our 9.0.8 server reported exactly that.
There is an exception interviewers like. In a primary-secondary-arbiter (PSA) set, the voting majority is 2, and only 2 members carry data. Because the number of data-bearing voters is not greater than the majority, the default falls back to w: 1.
17. Does MongoDB support ACID transactions?
Yes. Single-document writes have always been atomic. MongoDB also supports multi-document (distributed) transactions on replica sets and sharded clusters, which are atomic: all changes commit or none do. By default a transaction must finish within one minute. In 9.0 a server also accepts at most 10,000 concurrently open multi-document transactions by default.
const session = db.getMongo().startSession()
const acc = session.getDatabase("interview").accounts
session.startTransaction({ writeConcern: { w: "majority" } })
const r = acc.updateOne({ _id: "asha", balance: { $gte: 1500 } },
{ $inc: { balance: -1500 } })
if (r.modifiedCount !== 1) {
session.abortTransaction()
} else {
acc.updateOne({ _id: "ravi" }, { $inc: { balance: 1500 } })
session.commitTransaction()
}
// balances 5,000 / 1,000 -> 3,500 / 2,500 (committed)
// a second transfer of 9,000 from ravi failed the balance
// check and was aborted: nothing changed
A good answer adds MongoDB's own advice: transactions cost more than single-document writes and are not a replacement for a good schema. If two pieces of data must always change together, consider keeping them in one document.
18. What is sharding, and how do you choose a shard key?
Sharding splits a collection across replica sets called shards, so data and load can grow beyond one server. MongoDB divides the shard key's values into ranges called chunks and spreads them across shards. Range sharding keeps nearby keys together. Hashed sharding spreads data more evenly, but more queries then have to be broadcast to every shard instead of targeted to one.
A good shard key has many distinct values, spreads writes evenly and appears in your common queries. A key that grows monotonically, such as a timestamp or an auto-increasing number, is a poor range key on its own, because every new insert lands on the same "last" chunk.
Running MongoDB
19. How much RAM does MongoDB need?
There is no fixed minimum, but memory decides speed. By default the WiredTiger storage engine's cache takes the larger of 50% of (RAM − 1 GB) or 0.256 GB. The rest is used by the operating system's file cache, connections and queries. Aim for your working set (frequently used data plus indexes) to fit in RAM.
| Server RAM | Default WiredTiger cache | 9.0 per-operation memory limit |
|---|---|---|
| 1 GB | 0.256 GB | 1 GB |
| 2 GB | 0.5 GB | 1 GB |
| 8 GB | 3.5 GB | 1.6 GB |
| 16 GB | 7.5 GB | 3.2 GB |
We checked the cache formula on our test container, which reported 5,925 MB of RAM. 50% of (5,925 − 1,024) MB predicts 2,450 MiB, and serverStatus() reported 2,450 MiB.
20. What is new in MongoDB 9.0?
MongoDB 9.0 (GA 28 Sep 2026) adds a per-operation memory limit for queries, a default limit of 10,000 concurrent multi-document transactions and query statistics enabled by default. It also re-enables server-side JavaScript ($function, $accumulator, $where) on a sandboxed WebAssembly engine, and makes substring, prefix and suffix queries on Queryable Encryption fields generally available.
You will not be expected to know every release note. Knowing the current version, and one or two changes that affect everyday queries, shows that you keep up.
How should a fresher prepare for a MongoDB interview?
- Run MongoDB yourself:
docker run mongo:9.0, or a free Atlas cluster (MongoDB 8.0, 0.5 GB storage). Usemongosh, not just a GUI. - Build one small app end to end, such as an e-commerce database with customers, products and orders. Decide what to embed and what to reference, and be ready to explain why.
- For every query you write, run
explain("executionStats")and readtotalDocsExamined. Most indexing questions are answered by that one habit. - Write the same report in SQL and as an aggregation pipeline.
- Learn the numbers in this post: 16 MiB, 64 indexes, 50/7 members, majority = 1 + floor(n/2), the 100 MB stage limit, the WiredTiger cache formula.
Where can you learn MongoDB properly?
Skill-Lync's Everything about Database course teaches SQL and MongoDB side by side, including one-to-one and one-to-many relationships and advanced MongoDB queries (joins, sorting, grouping and indexing). The Post Graduate Program in Full Stack Web Development uses MongoDB inside complete web applications, with mentor-reviewed projects and placement support. You can talk to a Skill-Lync counsellor about which fits your background. If you are just starting out, read our beginner's guide to web development first.
Frequently asked questions
Is MongoDB free to use?
Yes, for most learners and companies. MongoDB Community Server is free to download and run under the Server Side Public License, and MongoDB Atlas has a free cluster with 0.5 GB of storage. The SSPL's extra conditions apply when you offer MongoDB itself to the public as a hosted service.
Is MongoDB SQL or NoSQL?
MongoDB is a NoSQL document database. It does not use tables or SQL as its query language; you query with JSON-like filter documents and aggregation pipelines through drivers or mongosh. It still offers many features people associate with SQL databases, including secondary indexes, joins through $lookup, and multi-document ACID transactions.
Which MongoDB version should I learn in 2026?
Learn on MongoDB 8.0 or 9.0. Version 9.0 became generally available on 28 Sep 2026, and Atlas's free tier runs 8.0. The query language, indexes and aggregation pipeline you will be asked about are the same in both. Mention the version you practised on, and one 9.0 change, in your interview.
Do I need to learn SQL before MongoDB?
It is not required, but it helps a lot. Many applications use both relational and document databases, and many interview questions ask you to compare them. Knowing joins, GROUP BY and normalisation makes it easier to explain when MongoDB's embedding, $lookup and $group are the better choice and when a relational table is.
How do I practise MongoDB queries without a big dataset?
Generate one. A short mongosh script with a loop can insert 100,000 synthetic orders in seconds, which is enough to see indexes and explain() behave realistically. Small toy collections of ten documents hide the performance effects interviewers ask about, so practise on data big enough for a missing index to show.
Sources and further reading
- MongoDB, Release Notes for MongoDB 9.0 (9.0.0 on 28 Sep 2026, 9.0.8 on 10 Nov 2026; per-operation memory limit, transaction limit, server-side JavaScript, Queryable Encryption), accessed 23 Nov 2026.
- MongoDB, MongoDB Limits and Thresholds, accessed 23 Nov 2026.
- MongoDB, ObjectId() and BSON Types, accessed 23 Nov 2026.
- MongoDB, The ESR (Equality, Sort, Range) Guideline and Explain Results, accessed 23 Nov 2026.
- MongoDB, Aggregation Pipeline Limits and $lookup, accessed 23 Nov 2026.
- MongoDB, Avoid Unbounded Arrays and Data Model Design, accessed 23 Nov 2026.
- MongoDB, Replica Set Members and Write Concern, accessed 23 Nov 2026.
- MongoDB, Transactions and Production Considerations, accessed 23 Nov 2026.
- MongoDB, Shard Keys, Choose a Shard Key and Hashed Sharding, accessed 23 Nov 2026.
- MongoDB, Indexes (B-tree) and GridFS, accessed 23 Nov 2026.
- MongoDB, WiredTiger Storage Engine (cache size formula), accessed 23 Nov 2026.
- MongoDB, Atlas Free Cluster Limits, accessed 23 Nov 2026.
- MongoDB, Server Side Public License FAQ, accessed 23 Nov 2026.
- Open Source Initiative, The SSPL is Not an Open Source License, 19 Jan 2021.
- GitHub, mongodb/mongo repository (language breakdown: mostly C++), accessed 23 Nov 2026.
- Skill-Lync public student project index, titles only, n = 177,222 project pages, read 23 Nov 2026.
- Skill-Lync Engineering Desk, test script and raw output for this article (worked.js on MongoDB 9.0.8, calc.py), 23 Nov 2026.


