Autocoder

MongoDB Interview Questions and Answers

Last updated 2026-11-19

MongoDB rounds for freshers and one-to-three-year developers follow a pattern: documents versus tables, a handful of CRUD and aggregation queries, indexing, replication and sharding. The queries below are written in mongosh syntax and can be run as shown against a small collection.

MongoDB sits in the document family described on the NoSQL interview questions page, and its transaction model is easier to follow after transactions and ACID. Backend candidates should also prepare REST API questions.

Data formatBSON documents in collections
Query toolsFind, aggregation pipeline, indexes
ScalingReplica sets and sharded clusters

Sample data used in the answers

Assume an orders collection with documents of the shape { _id, customer: "asha", status: "shipped", total: 1200, items: [ { sku: "A1", qty: 2 } ], created: ISODate(...) }. Most questions below can be answered by describing one query against this shape and the index that supports it.

Points interviewers listen for

MongoDB Interview Questions and Answers: questions with worked answers

  1. 1

    What is MongoDB, and how do documents differ from rows?

    easy

    MongoDB is a document database that stores records as BSON, a binary form of JSON, in collections. A document can contain nested objects and arrays, and documents in one collection need not share the same fields. A row has fixed columns of scalar values, while a document can hold an order with its line items inside it, avoiding joins for data read together. Each document has an _id primary key, by default an ObjectId, and a maximum size of 16 MB.

  2. 2

    What is an ObjectId?

    easy

    ObjectId is the default 12-byte _id type: a 4-byte timestamp in seconds, a 5-byte random value unique to the process and machine, and a 3-byte incrementing counter. It is generated by the driver without contacting the server, is roughly ordered by creation time, and lets you extract the creation time. It is unique in practice but not a security token, since it is guessable.

  3. 3

    Write queries to insert, find, update and delete documents.

    easy

    insertOne adds a document; find takes a filter and optional projection; updateOne takes a filter and an update operator document; deleteOne removes the first match. Use update operators such as $set and $inc, because passing a plain document to updateOne is rejected. updateMany and deleteMany affect all matches, and the upsert option inserts when no document matches.

    javascript
    db.orders.insertOne({ customer: "asha", status: "new", total: 1200 });
    db.orders.find({ total: { $gt: 1000 } }, { customer: 1, total: 1, _id: 0 });
    db.orders.updateOne({ customer: "asha" }, { $set: { status: "shipped" }, $inc: { total: 50 } });
    db.orders.deleteOne({ status: "cancelled" });
  4. 4

    Explain the aggregation pipeline with an example: total sales per customer, top three.

    medium

    The pipeline passes documents through ordered stages, each transforming the stream: $match filters, $group aggregates, $sort orders, $limit truncates, $project reshapes, $lookup joins and $unwind flattens arrays. Putting $match first reduces the work and can use an index. This query keeps shipped orders, sums totals per customer, sorts descending and returns three results.

    javascript
    db.orders.aggregate([
      { $match: { status: "shipped" } },
      { $group: { _id: "$customer", sales: { $sum: "$total" }, orders: { $sum: 1 } } },
      { $sort: { sales: -1 } },
      { $limit: 3 }
    ]);
  5. 5

    How do you query inside arrays and embedded documents?

    medium

    Use dot notation for embedded fields, as in "address.city". For arrays of scalars a plain equality matches if any element equals the value. For arrays of objects, plain dot notation can match different elements for different conditions, so use $elemMatch to require that one element satisfies all conditions: { items: { $elemMatch: { sku: "A1", qty: { $gte: 2 } } } } returns orders with a single item that has sku A1 and quantity at least 2. $size matches by array length and $all requires several values.

  6. 6

    How do indexes work in MongoDB, and what is a compound index?

    medium

    Indexes are B-tree structures, as in relational databases. The _id index is automatic. A compound index such as { customer: 1, created: -1 } is sorted by customer then created and serves queries on customer or on customer and created, following the leftmost-prefix rule, and can serve a sort in matching order. The ESR guideline orders fields as equality, sort, then range. Other types include multikey indexes on arrays, TTL indexes that delete expired documents, text, geospatial and partial indexes. Use explain("executionStats") and look for IXSCAN rather than COLLSCAN.

    javascript
    db.orders.createIndex({ customer: 1, created: -1 });
    db.orders.find({ customer: "asha" }).sort({ created: -1 }).explain("executionStats");
  7. 7

    Embedding versus referencing: how do you decide?

    medium

    Embed when the data is read together, belongs to one parent and has a bounded size: a blog post with a few comments, an order with its items. You get one read and atomic updates. Reference when the child set is large or unbounded, is shared across parents, or is updated independently: a user and millions of events. Referencing needs a second query or $lookup. Also remember the 16 MB document limit and that an ever-growing array hurts update performance.

  8. 8

    What is a replica set and how does failover work?

    medium

    A replica set is a group of mongod nodes holding the same data: one primary accepts writes and secondaries replicate from its oplog. If the primary becomes unreachable, the remaining members hold an election and a majority vote chooses a new primary, usually within seconds. This needs a voting majority, so use an odd number of voting members, and an arbiter if you need a tie-break without storing data. Drivers reconnect automatically and can retry writes.

  9. 9

    Explain write concern and read concern.

    medium

    Write concern states how many members must acknowledge a write: w:1 means the primary only, w:"majority" means a majority of voting members have it, and j:true waits for the journal. Majority writes survive a primary failover without rollback. Read concern sets the consistency of reads: local returns the node's latest data, majority returns data acknowledged by a majority, and linearizable and snapshot are stronger levels. Higher levels add latency, so use majority for important data and local for dashboards.

  10. 10

    How does sharding work and how do you pick a shard key?

    hard

    A sharded cluster splits a collection across shards, each a replica set. mongos routers send queries using cluster metadata from config servers, and chunks of key ranges are balanced between shards. The shard key decides everything: it needs high cardinality, even write distribution and presence in common queries so they target one shard. A monotonically increasing key such as a timestamp or ObjectId sends all inserts to one shard; a hashed key spreads them but makes range queries scatter-gather. Since MongoDB 5.0 you can reshard a collection, though it is heavy.

  11. 11

    Does MongoDB support transactions?

    medium

    Operations on a single document are always atomic, including its nested arrays, which is why modelling related data in one document avoids transactions. Multi-document ACID transactions arrived in 4.0 for replica sets and 4.2 for sharded clusters. They use snapshot isolation, have a default 60-second runtime limit, and cost more than single-document writes, so use them for genuinely cross-document invariants such as moving money between accounts.

  12. 12

    How does $lookup work, and what is its limitation?

    medium

    $lookup performs a left outer join from the pipeline's collection to another, adding matched documents as an array. It is useful but not a relational join engine: it works best with an indexed foreign field, is not efficient for joining huge collections, and across shards it can require scatter-gather. If you $lookup constantly, the model probably needs embedding.

    javascript
    db.orders.aggregate([
      { $lookup: { from: "customers", localField: "customer", foreignField: "_id", as: "cust" } },
      { $unwind: "$cust" }
    ]);
  13. 13

    What is a TTL index?

    easy

    A TTL index deletes documents automatically once a date field is older than a set number of seconds. createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }) removes documents about an hour after createdAt. A background task runs about once a minute, so deletion is not instant. It suits sessions, OTPs and temporary logs.

  14. 14

    How would you find and fix a slow query in MongoDB?

    hard

    Enable the profiler or inspect the slow query log, then run explain("executionStats") on the query. Compare totalDocsExamined with nReturned: a large gap means poor selectivity, and a COLLSCAN stage means no usable index. Create a compound index following equality, sort, range order, re-run explain and confirm IXSCAN and fewer examined documents. Also check for a sort that exceeds memory, an unanchored regex that cannot use an index and projections that could make the query covered.

Frequently asked questions

Is MongoDB schemaless?

It is schema-flexible. You can enforce structure with JSON Schema validation on a collection, and most applications keep a de facto schema in their models.

What is the difference between find and aggregate?

find filters and projects documents. aggregate runs multi-stage pipelines that can group, join, reshape and compute, so use it for reporting.

Can MongoDB replace a relational database?

For many applications yes, but workloads with complex multi-table transactions and ad hoc joins are usually easier in a relational database.

Which language should I use for MongoDB practice?

Practise in mongosh with JavaScript syntax, then repeat in the driver for your stack, such as PyMongo or the Node.js driver.

Related guides

More in CS Fundamentals Interview Questions

See all in this section