MongoDB Interview Questions and Answers (2026)

MongoDB interview questions with answers: documents, CRUD, indexes, aggregation, replica sets, sharding, and 10 practice queries.

PragadeeshOctober 22, 2026
MongoDB Interview Questions and Answers (2026)
Summarize this article in
Quick Answer
  • MongoDB interview questions with answers: documents, CRUD, indexes, aggregation, replica sets, sharding, and 10 practice queries.
  • Open any question for a short answer you can say in the round.
  • Use the FAQ if you only have a few minutes before the test.

MongoDB interview questions with answers start from the document model: a record is a BSON document in a collection, not a row locked to a table schema. This 2026 set follows the usual interview order — basics, CRUD, indexes, aggregation, replication, sharding, then ten practice queries on a sample collection. Behaviour that must be exact is in the MongoDB manual.

1. How is MongoDB different from a relational database?

MongoDB keeps each record as a document. A relational database keeps each record as a row with a fixed list of columns.

  • Shape. Documents can nest objects and arrays. Rows cannot, so related facts become more tables.
  • Schema. A collection can hold documents with different fields. A table rejects a row that misses a required column unless you planned for nulls.
  • Relationships. MongoDB embeds the child inside the parent, or stores an id and looks it up. SQL declares a foreign key and joins.
  • Scale-out. MongoDB splits a collection with sharding. Most SQL systems grow by buying a larger server first.
  • Query language. You pass a query document. SQL is a separate language. The ideas still map: filter, project, group, sort. Practise both with the SQL interview questions.

2. What is a document, and what is a collection?

A document is one record: field names and values, stored as BSON and usually written like JSON. A collection is the set of those documents, roughly where a table would sit. Documents in one collection should describe the same kind of thing, such as learners, even if one learner has a phone field and another does not.

{
  _id: ObjectId("66ab10c2e1d4a9b0c3110001"),
  name: "Meera",
  city: "Chennai",
  skills: ["JavaScript", "MongoDB"]
}

3. How does MongoDB store data on disk?

The server writes BSON, not the text you typed in the shell. Collections live inside a database, and the default storage engine, WiredTiger, keeps the data files and the indexes. You do not place those files by hand. You choose a database name and a collection name; WiredTiger handles pages, compression, and the cache.

4. What is BSON, and why is it used?

BSON is binary JSON. It keeps the document model and adds types JSON text does not have, including dates, raw binary, and ObjectId. The binary layout is quicker to scan than a string, which is why queries and indexes walk BSON rather than pretty-printed JSON. When you see a document in Compass, you are looking at a view of that binary form.

5. Which data types can a document hold?

  • String, boolean, and null.
  • Numbers: 32-bit integer, 64-bit integer, double, and Decimal128 for money.
  • Date, in UTC.
  • Array, which may mix types.
  • Embedded document.
  • ObjectId, binary, regular expression, timestamp, and JavaScript code (rare in application data).

Pick Decimal128 for fees and salaries. A double will surprise you on paisa. Store dates as Date, not as strings, or range filters and TTL indexes will not behave.

6. How do you create a database and a collection?

In mongosh, use campus switches to that database and remembers it if it is new. The database appears on disk after the first write. db.createCollection("learners") creates an empty collection. An insert into a missing collection also creates it, which is fine in a lab and sloppy if you needed a validator on day one.

use campus
db.createCollection("learners")

7. How does MongoDB stay available when a server fails?

A replica set copies the data to more than one server. Clients write to the current primary. If that primary stops, the remaining members elect another. Sharding is the other half: it spreads a large collection across many replica sets so one machine is not the whole dataset. Availability is the replica set. Growth past one replica set is sharding.

8. What does the _id field do?

_id is the primary key of the document. The collection keeps a unique index on it. If you omit it, the server adds an ObjectId. You can set your own unique value, but do not use a mutable email address. ObjectId values are unique across servers and roughly time-ordered. They are not a business clock and not a secret.

9. How do you insert one document or many?

insertOne writes a single document and returns its id. insertMany writes a list. A repeated _id fails that insert. Write the document in full in an interview before you write the method name, so the panel sees the shape.

db.learners.insertOne({
  name: "Meera",
  city: "Chennai",
  track: "Database",
  score: 78
})

10. What is a replica set?

A replica set is a group of mongod processes with the same data. One primary takes writes. Secondaries apply the primary's oplog. You can allow secondaries to serve reads. When the primary is lost, an election promotes a secondary. Say that, then stop. The election protocol is not a junior coding question. Official detail is in the replication documentation.

11. What is sharding?

Sharding partitions a collection by a shard key. Each shard holds a range or a hashed slice of that key. A router, mongos, sends each query to the right shards. MongoDB can move chunks to balance them. A shard key that sends every write to one shard wastes the cluster. Name the key from the query you actually run, and do not invent a production key in a first-round interview.

12. What do the four CRUD operations look like?

Create, read, update, and delete are methods on the collection. The CRUD page is the reference if a flag name slips.

  • Create: db.learners.insertOne({ name: "Arun", score: 71 })
  • Read: db.learners.find({ name: "Arun" })
  • Update: db.learners.updateOne({ name: "Arun" }, { $set: { score: 80 } })
  • Delete: db.learners.deleteOne({ name: "Arun" })

13. How do you filter documents?

find takes a query document. Equality is a field and a value. Comparisons use operators: $gt, $gte, $lt, $lte, $in, $ne. A second document is the projection: 1 keeps a field, 0 drops it. Do not mix includes and excludes, except for dropping _id.

db.learners.find(
  { city: "Chennai", score: { $gte: 70 } },
  { name: 1, score: 1, _id: 0 }
)

14. What is an index, and how do you create one?

An index is an ordered side structure on one or more fields so a filter or sort does not walk every document. _id is indexed already. You add others with createIndex. 1 is ascending, -1 is descending.

db.learners.createIndex({ city: 1, score: -1 })

Lead a compound index with the equality field. An index on score alone is a weak match for "Chennai, highest score first." Indexes speed reads and slow writes, so add the ones your screens use. See the index documentation.

15. How does MongoDB keep writes consistent?

Three knobs come up in interviews. Journaling writes an operation to a log before it is called durable, so a crash can replay it. Write concern says how many members must acknowledge the write: the primary only, or the primary and a secondary. Read concern says how fresh a read must be. Replica sets copy the data so a lost primary does not lose the acknowledged writes. Pick the concern from the product rule, not from a default you never read.

16. How do you import and export data?

mongoimport loads JSON, CSV, or TSV into a collection. mongoexport writes a collection back out. They are fine for a one-off file. A full backup of a running database is mongodump and mongorestore, which keep BSON and indexes more faithfully than a CSV.

mongoimport --db campus --collection learners --file learners.json
mongoexport --db campus --collection learners --out learners.json

17. What is an aggregation pipeline?

Aggregation runs documents through stages. Each stage reads the previous stage's output. $match filters, $group folds rows together, $sort orders, $project reshapes. Put $match first so later stages see fewer documents. The aggregation guide lists every stage; do not invent operators.

db.learners.aggregate([
  { $match: { city: "Chennai" } },
  { $group: { _id: "$track", total: { $sum: 1 } } },
  { $sort: { total: -1 } }
])

18. Which aggregation stages should you know first?

Learn five before you collect rare ones. $match is the filter. $group needs an _id and accumulators such as $sum, $avg, $max, and $push. $sort takes 1 or -1. $limit and $skip page the result. $project or $set builds the fields you want to show. $lookup pulls from another collection when you refused to embed. If you can narrate match, then group, then sort, you can answer most junior pipeline questions.

19. What is write concern?

Write concern is the acknowledgement rule for a write. w: 1 returns after the primary applies it. w: "majority" returns after enough members have it that an election cannot drop it. A journal option asks for the on-disk log as well. Weaker concern is quicker and riskier. Stronger concern is slower and safer. Say which one you would use for a payment, and which one you would use for a click counter. Those two answers show you understand the knob.

20. What is a TTL index?

A TTL index deletes documents after a time, using a date field. Session rows and one-time codes are the usual fit. A background task does the delete, so expiry is not a stopwatch. Do not put a TTL index on records you must keep, such as invoices.

db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 3600 }
)

21. How should you model data: embed or reference?

Embed when the child is small, has a bound, and is always read with the parent. A learner's address belongs on the learner. Reference when the child is large, shared, or opened on its own screen. A course taken by hundreds of learners should live in a courses collection if the title changes in one place. Never embed a log that grows forever. The document size limit is 16 megabytes, and huge arrays make every update clumsy. Pay context for this skill is in the MongoDB salary guide, which is a planning band, not an offer.

22. What is WiredTiger?

WiredTiger is the storage engine MongoDB uses. It compresses data, caches pages, and allows document-level concurrency so two writes to different documents do not block each other the way an older engine could. MMAPv1 is the retired engine. If a question names both, say WiredTiger replaced it and you would not deploy MMAPv1. You do not need its file format. You need to know it is the current engine and that the cache size matters on a small server.

23. How do transactions work?

A single-document update is already atomic. You do not need a transaction to $inc one counter. A multi-document transaction wraps several reads and writes, including across collections, and commits or aborts them together. Replica sets support them. Use one when a business rule crosses documents, such as moving a seat from one batch to another. They cost more than a single write, so do not wrap every insert. The transactions page shows the session API.

24. What is MongoDB Compass?

Compass is the official graphical client. You browse databases, edit a document, build a query with a form, look at an explain plan, and draw a simple aggregation. It is a learning tool and a support tool. It is not a substitute for the shell in an interview. If the panel asks you to write the query, write the method. Mention Compass only as the place you inspect data.

25. What is MongoDB Atlas?

Atlas is MongoDB's managed cloud service. It runs the servers, backups, and patches. A self-hosted deployment means you install mongod, open the port, rotate credentials, and take backups yourself. Atlas is still MongoDB: the same drivers, the same query language. The difference is who operates the machines. For a laptop exercise, a local server or a free Atlas cluster both work.

26. How do you require a login?

Start MongoDB with authorization enabled, create an admin user, then create a user on the application database with only the roles that user needs. The application connects with that user, not with a wide-open port. Do not commit the connection string. Pass field values from the request; do not merge raw JSON into a query object, because a user can smuggle operators such as $gt. "NoSQL cannot be injected" is false.

27. What is a capped collection?

A capped collection is a fixed-size ring. New inserts overwrite the oldest documents once the cap is full. Insertion order is preserved. It fits a short activity tail, not a system of record. You cannot delete a single document from a classic capped collection the way you delete from a normal one, so do not pick it for learners or payments.

28. What is a geospatial index?

A 2dsphere index supports queries on GeoJSON points, such as "learners within 5 kilometres of this classroom." You store a location field as a point with coordinates in longitude, then latitude. createIndex({ location: "2dsphere" }) builds it. $near or $geoWithin queries it. If you swap latitude and longitude, the points land in the wrong place. Say that check out loud.

29. How do you back up a database?

Use mongodump for a logical backup and mongorestore to load it. On a replica set, dump from a secondary if you must avoid loading the primary. Atlas and volume snapshots are the other common paths. A backup you have never restored is a guess. In an interview, say what you would dump, where you would store it, and that you would test a restore. Filesystem copies of a live WiredTiger directory, taken without a proper snapshot, can tear.

30. How do you upgrade MongoDB?

Read the release notes for the versions you will cross. Upgrade one major version at a time. On a replica set, upgrade secondaries first, step down the primary, then upgrade that member. Take a backup before you start. Application drivers often need a matching upgrade. Skipping from a very old version straight to the newest is how a lab upgrade becomes an outage.

31. What is a change stream?

A change stream is a live feed of inserts, updates, and deletes on a collection, a database, or a whole deployment. You resume it with a token if the listener drops. Applications use it to update a cache or to publish events. It needs a replica set, because it reads the oplog. It is not a trigger inside the database. Your process has to stay running.

32. What is a hashed shard key?

A hashed shard key spreads writes by the hash of a field, often _id, so consecutive inserts do not all land on the last chunk. That balances writes. It makes range queries on that field visit more shards, because nearby values are not stored together. Use a hashed key when the workload is write-heavy and you rarely query a range of the key. Use a ranged key when you constantly ask for "this city" or "this month."

33. How do you speed up a slow query?

Run explain and look for a collection scan on a large collection. Add an index that matches the filter and the sort. Project only the fields you display. Filter at the start of an aggregation. Avoid unbounded $lookup on a hot path. Check that the working set fits in RAM before you blame the query. A missing index is the usual junior bug. A query that returns the entire collection is the usual product bug.

34. What happened to map-reduce?

Map-reduce was an older way to run custom JavaScript over a collection. Aggregation replaced it for almost every interview example: it is faster, easier to read, and does not need custom functions for sums and counts. If a panel still says map-reduce, answer that you would write a pipeline, and use a function only if no stage can express the rule. Do not lead with map-reduce in 2026.

35. What is journaling?

Journaling is the write-ahead log. MongoDB records the operation in the journal before it treats the write as durable. After a crash, it replays that log. Turning journaling off, or acknowledging writes before the journal, makes a crash lose recent writes. The cost is extra disk traffic. For data you cannot recreate, leave journaling on and use a write concern that waits for it.

Create a text index on the string fields you want to search, then query with $text. One collection can have only one text index, and that index can cover several fields. It is a basic keyword search, not a full search engine. Atlas Search is the heavier option when you need language analyzers and relevance tuning. For a junior round, the text index and $text are enough.

db.learners.createIndex({ name: "text", track: "text" })
db.learners.find({ $text: { $search: "database" } })

37. What belongs in a production deployment?

A replica set of at least three voting members, authorization turned on, TLS on the network, backups that have been restored once, and monitoring on disk, connections, and replication lag. The application uses a narrow database user. The port is not open to the internet. Indexes match the real queries. You have a tested upgrade path. A single mongod on a laptop is not that list, and saying so is a good answer.

38. How does horizontal scaling work?

Horizontal scaling means adding machines, not only a bigger CPU. In MongoDB that is sharding: more shards, each a replica set, with mongos in front. Vertical scaling means a larger primary, which helps until the box cannot grow. Say both, then say you would shard only after the working set and the write rate no longer fit one replica set. Sharding a tiny collection adds a router and a shard key you can get wrong.

39. How do you notice a performance problem?

Watch operation time in the profiler or in Atlas metrics, replication lag, cache pressure, and the number of connections. A sudden collection scan in the slow log usually means a new query shipped without an index. A lagging secondary means reads from it are stale and a failover would be slow. Start from the slow operation, not from a random restart.

40. How do you move a SQL table into MongoDB?

List the screens first. Tables that are always read together can become one document. Tables that are large or shared stay as collections, and you store the old primary key as a field you index. Export CSV, import with mongoimport, then build indexes and check counts against SQL. Do not translate every foreign key into $lookup and call it a design. A join-for-join copy keeps the SQL pain and loses the document model's one-read screens.

Practice queries on a sample collection

Use this shape. Answers below are the queries, not a dump of every document.

db.learners.insertMany([
  { name: "Meera", track: "Database", city: "Chennai", score: 82, joined: ISODate("2026-01-12") },
  { name: "Arun", track: "Backend", city: "Chennai", score: 74, joined: ISODate("2026-02-02") },
  { name: "Diya", track: "Database", city: "Coimbatore", score: 91, joined: ISODate("2025-11-20") }
])

41. Find every learner on the Database track

db.learners.find({ track: "Database" })

Equality is the field name and the value. Add a projection if the panel only wants names.

42. Find the learner with the highest score

db.learners.find().sort({ score: -1 }).limit(1)

Sort descending and keep one document. An index on score helps when the collection is large. $group with $max returns the number, not the whole learner, so use it only when they asked for the score.

43. Set Arun's score to 80

db.learners.updateOne(
  { name: "Arun" },
  { $set: { score: 80 } }
)

$set changes one field. Without it, the update replaces the document and the city disappears.

44. Count learners on each track

db.learners.aggregate([
  { $group: { _id: "$track", count: { $sum: 1 } } }
])

_id in $group is the group key, here the track. $sum: 1 counts documents.

45. Add a bonus field for the Database track

db.learners.updateMany(
  { track: "Database" },
  { $set: { bonus: 5000 } }
)

updateMany is deliberate. updateOne would change only Meera or only Diya, whichever the scan hit first.

46. Sort learners by name length

db.learners.aggregate([
  { $set: { nameLength: { $strLenCP: "$name" } } },
  { $sort: { nameLength: -1 } }
])

$strLenCP counts characters. A normal sort on name is alphabetical, which is a different question. Listen for the word "length."

47. Average score on the Database track

db.learners.aggregate([
  { $match: { track: "Database" } },
  { $group: { _id: null, average: { $avg: "$score" } } }
])

Match first, then average. _id: null means one group for every document that survived the match.

48. Which track has the highest average score?

db.learners.aggregate([
  { $group: { _id: "$track", average: { $avg: "$score" } } },
  { $sort: { average: -1 } },
  { $limit: 1 }
])

Group, sort the averages, keep the top row. Limiting before the group would answer a different question.

49. How many learners joined in each year?

db.learners.aggregate([
  { $group: {
      _id: { $year: "$joined" },
      count: { $sum: 1 }
  } }
])

joined must be a Date. A string date makes $year fail or return nothing useful.

50. Highest and lowest Database score

db.learners.aggregate([
  { $match: { track: "Database" } },
  { $group: {
      _id: null,
      high: { $max: "$score" },
      low: { $min: "$score" }
  } }
])

One group can carry both $max and $min. You do not need two queries.

Where to go next

Build the ten practice queries on your own machine, then explain embed versus reference with one project. The topic list for class is the MongoDB course syllabus, and the wider stack is full stack training in Chennai. Roles that use this database day to day are outlined in the MERN salary guide. More sets sit in the interview questions category.

Frequently Asked Questions

What is MongoDB?
MongoDB is a document database. Each record is a BSON document in a collection. Fields can nest and can differ between documents, and the team can still validate a schema.
How is MongoDB different from SQL?
SQL stores rows in fixed tables and joins them. MongoDB stores documents, embeds related data or references it, and uses a query document instead of SQL.
How do you update a single field?
Call updateOne or updateMany with $set. An update without an operator replaces the whole document.
What is an aggregation pipeline?
It is a list of stages. $match filters, $group summarises, $sort orders, and $project reshapes. Filter early so later stages see fewer documents.
What is a replica set?
A replica set is a group of servers with the same data. One primary takes writes. If it fails, a secondary can be elected.
When should you embed a document?
Embed when the child is small, bounded, and always read with the parent. Keep a separate collection when the child is large, shared, or queried on its own.

Pragadeesh

Asmorix mentors share practical guidance on software, cloud, data, testing, and placement preparation for learners in Chennai.

View more posts

Call Now 81900 98289