Interview Q&A

Pick a topic — languages & databases — 100+ questions and answers in the center column.

MongoDB

Interview questions & answers

Documents, aggregation, replica sets, sharding.

102 questions

  1. Question 1

    What is MongoDB?

    Document-oriented NoSQL database storing BSON JSON-like documents in collections. Horizontally scalable via sharding, high availability via replica sets; popular for flexible schema and rapid iteration.

    Example code

    db.runCommand({ ping: 1 })
  2. Question 2

    Document vs row?

    Documents are nested maps/arrays—embed vs reference models trade query locality vs update isolation.

    Example code

    db.users.insertOne({ name: "Ada", tags: ["dev"] })
  3. Question 3

    What is BSON?

    Binary JSON superset with extra types (ObjectId, Decimal128, Date)—efficient encoding and traversal on wire and disk.

    Example code

    ObjectId()
  4. Question 4

    ObjectId?

    12-byte value: timestamp + random + counter—roughly sortable by creation time; not guaranteed monotonic under load.

    Example code

    db.coll.find({ _id: ObjectId("507f1f77bcf86cd799439011") })
  5. Question 5

    Collections and databases?

    Database contains collections; collections contain documents—no rigid schema but indexes enforce access patterns.

    Example code

    db.coll.insertOne({})
  6. Question 6

    What is _id?

    Required unique key per document; auto-generated ObjectId if omitted—shard key consideration in clusters.

    Example code

    db.coll.find({ age: { $gt: 21 } })
  7. Question 7

    CRUD basics?

    insertOne/Many, find with filter, update with operators, replaceOne, delete—operations are atomic per document.

    Example code

    db.coll.updateOne({ _id: 1 }, { $set: { x: 1 } })
  8. Question 8

    Query operators?

    $gt, $in, $regex, $elemMatch, $exists—compose in filter objects for rich predicates.

    Example code

    db.coll.aggregate([{ $match: { a: 1 } }, { $group: { _id: "$b", c: { $sum: 1 } } }])
  9. Question 9

    Update operators?

    $set, $inc, $push, $pull, $unset—field-level updates without full document replace.

    Example code

    db.orders.aggregate([{ $lookup: { from: "items", localField: "_id", foreignField: "orderId", as: "items" } }])
  10. Question 10

    Aggregation pipeline?

    Stages ($match, $group, $lookup, $project) process documents in sequence—push filters early for performance.

    Example code

    db.coll.createIndex({ a: 1, b: -1 })
  11. Question 11

    $lookup?

    Left outer join to another collection—can be heavy; denormalize when read-heavy.

    Example code

    db.coll.find({ a: 1 }, { _id: 0, a: 1 })
  12. Question 12

    Indexes in MongoDB?

    Single/compound, multikey on arrays, text, geospatial, wildcard—explain() plans like SQL EXPLAIN.

    Example code

    rs.status()
  13. Question 13

    Covered queries?

    When projection includes only indexed fields and index can satisfy query—no document fetch.

    Example code

    rs.conf()
  14. Question 14

    Replica set?

    Primary + secondaries; automatic failover; read concern/read preference tune staleness vs scale-out reads.

    Example code

    { w: "majority", j: true }
  15. Question 15

    Election and heartbeat?

    Majority elects new primary if old dies—arbiter nodes vote without data (use sparingly).

    Example code

    "majority"
  16. Question 16

    Write concern?

    Ack levels w: majority vs w:1—durability vs latency; journal sync options.

    Example code

    session.startTransaction()
  17. Question 17

    Read concern?

    local, majority, linearizable—balance monotonic reads and causal consistency features.

    Example code

    sh.status()
  18. Question 18

    Transactions?

    Multi-document ACID since 4.0 in replica sets; sharded transactions later—higher overhead than single-doc ops.

    Example code

    sh.splitFind("test.users", { _id: 50 })
  19. Question 19

    Sharding?

    Shard key choice is critical—hot shards from poorly chosen keys; zone sharding for geo or tenant isolation.

    Example code

    mongos --configdb cfg/...
  20. Question 20

    Chunk migration?

    Balancer moves chunks between shards—impacts load; jumbo chunks block balance until split.

    Example code

    db.coll.watch([{ $match: { operationType: "insert" } }])
  21. Question 21

    mongos?

    Router for sharded cluster—stateless; config servers hold metadata; add more for router throughput.

    Example code

    db.createCollection("c", { validator: { $jsonSchema: { bsonType: "object" } } })
  22. Question 22

    Change Streams?

    Tail oplog-backed change feed—resume tokens for exactly-once style consumers at app level.

    Example code

    db.coll.createIndex({ t: 1 }, { expireAfterSeconds: 3600 })
  23. Question 23

    Schema validation?

    $jsonSchema in validator—optional structure enforcement without losing document model.

    Example code

    db.coll.find({ $text: { $search: "mongo" } })
  24. Question 24

    TTL indexes?

    Expire documents after a Date field + offset—background removal, not precise to the second.

    Example code

    bucket.files.find()
  25. Question 25

    Text search?

    $text with text index—basic BM25 scoring; Atlas Search richer for production search UX.

    Example code

    mongodb+srv://user:pass@cluster.mongodb.net/db
  26. Question 26

    GridFS?

    Chunk large files across documents—driver API; object storage often simpler for blobs.

    Example code

    db.coll.find().explain("executionStats")
  27. Question 27

    Connection string?

    mongodb[+srv]://user:pass@hosts/db?options—TLS, retryWrites, readPreference query params.

    Example code

    db.serverStatus().wiredTiger.cache
  28. Question 28

    Compass vs mongosh?

    GUI vs shell—both issue same commands; scripts often use mongosh --file.

    Example code

    db.serverStatus().wiredTiger
  29. Question 29

    explain('executionStats')?

    Winning plan, docs examined vs returned—high examination ratio signals missing/wrong index.

    Example code

    db.getSiblingDB("local").oplog.rs.find().limit(1)
  30. Question 30

    Memory limits?

    WiredTiger cache (formerly majority of RAM)—OS file cache also helps; monitor resident vs mapped.

    Example code

    mongodump --uri="mongodb://localhost"
  31. Question 31

    WiredTiger?

    Default storage engine—document-level concurrency, compression, checkpoints.

    Example code

    db.createUser({ user: "app", pwd: "x", roles: ["readWrite"] })
  32. Question 32

    Oplog?

    Capped replication log—size affects replica catch-up window; too small risks full resync.

    Example code

    db.coll.aggregate([{ $group: { _id: "$x", n: { $sum: 1 } } }], { allowDiskUse: true })
  33. Question 33

    Backup strategies?

    mongodump logical; filesystem snapshots for consistent physical; Atlas continuous backup managed.

    Example code

    // max document 16MB BSON
  34. Question 34

    Security checklist?

    Auth + TLS, least-privilege roles, network binding, field-level encryption for sensitive paths.

    Example code

    // prefer SQL/relational when heavy cross-row constraints
  35. Question 35

    Role-based access?

    Built-in roles + custom—database and collection granularity; test with application user.

    Example code

    db.stats()
  36. Question 36

    Aggregation allowDiskUse?

    Large sorts/group stages spill to disk—slower but avoids memory cap failures.

    Example code

    db.coll.deleteMany({ status: "draft" })
  37. Question 37

    BSON size limit?

    16MB max document—design splits or GridFS for larger payloads.

    Example code

    db.coll.replaceOne({ _id: 1 }, { _id: 1, name: "new" })
  38. Question 38

    When not to use MongoDB?

    Heavy multi-row ACID across many entities, strong relational constraints, or team lacks operational maturity for clusters.

    Example code

    db.adminCommand({ listDatabases: 1 })
  39. Question 39

    What is Atlas (MongoDB)?

    Managed MongoDB—automated backups, scaling UI, global clusters; vendor lock tradeoffs.

    Example code

    // MongoDB: Atlas
    db.runCommand({ ping: 1 })
  40. Question 40

    What is M10 vs dedicated (MongoDB)?

    Shared tier vs dedicated cluster—noisy neighbor vs predictable performance.

    Example code

    // MongoDB: M10 vs dedicated
    db.runCommand({ ping: 1 })
  41. Question 41

    What is VPC peering Atlas (MongoDB)?

    Private networking to app tier—security over public internet with allowlists.

    Example code

    // MongoDB: VPC peering Atlas
    db.runCommand({ ping: 1 })
  42. Question 42

    What is Private Endpoint (MongoDB)?

    Cloud provider private link—tightest network path to Atlas.

    Example code

    // MongoDB: Private Endpoint
    db.runCommand({ ping: 1 })
  43. Question 43

    What is Ops Manager / Cloud Manager (MongoDB)?

    Enterprise automation—monitoring, backup, automation agents.

    Example code

    // MongoDB: Ops Manager / Cloud Manager
    db.runCommand({ ping: 1 })
  44. Question 44

    What is mongostat / mongotop (MongoDB)?

    Live server stats—throughput and hot collections quick view.

    Example code

    // MongoDB: mongostat / mongotop
    db.runCommand({ ping: 1 })
  45. Question 45

    What is profiler (MongoDB)?

    Slow op logging—watch overhead; use sampling in prod.

    Example code

    // MongoDB: profiler
    db.runCommand({ ping: 1 })
  46. Question 46

    What is currentOp / killOp (MongoDB)?

    Inspect and terminate long operations—care with replication implications.

    Example code

    // MongoDB: currentOp / killOp
    db.runCommand({ ping: 1 })
  47. Question 47

    What is db.currentOp (MongoDB)?

    Filter by secs_running, ns—find stuck aggregations.

    Example code

    // MongoDB: db.currentOp
    db.runCommand({ ping: 1 })
  48. Question 48

    What is index builds (MongoDB)?

    Foreground vs background (deprecated patterns)—modern builds online with constraints per version.

    Example code

    // MongoDB: index builds
    db.runCommand({ ping: 1 })
  49. Question 49

    What is partialFilterExpression (MongoDB)?

    Sparse targeted indexes—smaller and faster for filtered queries.

    Example code

    // MongoDB: partialFilterExpression
    db.runCommand({ ping: 1 })
  50. Question 50

    What is collation (MongoDB)?

    Locale-aware sort/compare—index must match collation for efficient plans.

    Example code

    // MongoDB: collation
    db.runCommand({ ping: 1 })
  51. Question 51

    What is case insensitive index (MongoDB)?

    Collation strength 2—email login style lookups.

    Example code

    // MongoDB: case insensitive index
    db.runCommand({ ping: 1 })
  52. Question 52

    What is wildcard index (MongoDB)?

    Index arbitrary subfields—flexible schema cost: larger index.

    Example code

    // MongoDB: wildcard index
    db.runCommand({ ping: 1 })
  53. Question 53

    What is hidden index (MongoDB)?

    Test drop impact without removing—hide from planner temporarily.

    Example code

    // MongoDB: hidden index
    db.runCommand({ ping: 1 })
  54. Question 54

    What is hint() (MongoDB)?

    Force plan—last resort; planner changes version to version.

    Example code

    // MongoDB: hint()
    db.runCommand({ ping: 1 })
  55. Question 55

    What is plan cache (MongoDB)?

    Plans cached per shape—clear with planCacheClear after index changes.

    Example code

    // MongoDB: plan cache
    db.runCommand({ ping: 1 })
  56. Question 56

    What is facet stage (MongoDB)?

    Multiple aggregation pipelines in parallel—dashboard style multi-bucket reports.

    Example code

    // MongoDB: facet stage
    db.runCommand({ ping: 1 })
  57. Question 57

    What is bucket pattern (MongoDB)?

    Time-series grouping into pre-aggregated buckets—reduce document count.

    Example code

    // MongoDB: bucket pattern
    db.runCommand({ ping: 1 })
  58. Question 58

    What is out merge stages (MongoDB)?

    $out writes collection; $merge upserts—ETL patterns inside Mongo.

    Example code

    // MongoDB: out merge stages
    db.runCommand({ ping: 1 })
  59. Question 59

    What is graphLookup (MongoDB)?

    Recursive traversal—limited depth; graph DBs better for deep graphs.

    Example code

    // MongoDB: graphLookup
    db.runCommand({ ping: 1 })
  60. Question 60

    What is unionWith (MongoDB)?

    Combine collections in pipeline—analytics across heterogeneous sources.

    Example code

    // MongoDB: unionWith
    db.runCommand({ ping: 1 })
  61. Question 61

    What is densify / fill (time series) (MongoDB)?

    Gap filling for charts—time series collection helpers.

    Example code

    // MongoDB: densify / fill (time series)
    db.runCommand({ ping: 1 })
  62. Question 62

    What is time series collections (MongoDB)?

    Optimized storage for metrics—metaField and timeField schema.

    Example code

    // MongoDB: time series collections
    db.runCommand({ ping: 1 })
  63. Question 63

    What is $expr (MongoDB)?

    Aggregation expressions inside find—powerful but cannot use all index paths.

    Example code

    // MongoDB: $expr
    db.runCommand({ ping: 1 })
  64. Question 64

    What is aggregation allowDiskUse (MongoDB)?

    Spill to disk for large pipelines—set when memory errors occur.

    Example code

    // MongoDB: aggregation allowDiskUse
    db.runCommand({ ping: 1 })
  65. Question 65

    What is read preference secondary (MongoDB)?

    Scale reads—eventual consistency; hedge reads optional.

    Example code

    // MongoDB: read preference secondary
    db.runCommand({ ping: 1 })
  66. Question 66

    What is read preference nearest (MongoDB)?

    Lowest latency member—good for global apps with local secondaries.

    Example code

    // MongoDB: read preference nearest
    db.runCommand({ ping: 1 })
  67. Question 67

    What is tags in replica sets (MongoDB)?

    Target reads to specific data centers—operational control.

    Example code

    // MongoDB: tags in replica sets
    db.runCommand({ ping: 1 })
  68. Question 68

    What is write retryability (MongoDB)?

    Idempotent writes with retryWrites—duplicate key handling in app.

    Example code

    // MongoDB: write retryability
    db.runCommand({ ping: 1 })
  69. Question 69

    What is findAndModify (MongoDB)?

    Atomic single-doc read-update—compare with transactions overhead.

    Example code

    // MongoDB: findAndModify
    db.runCommand({ ping: 1 })
  70. Question 70

    What is bulkWrite (MongoDB)?

    Ordered vs unordered batches—throughput vs error stop semantics.

    Example code

    // MongoDB: bulkWrite
    db.runCommand({ ping: 1 })
  71. Question 71

    What is ordered inserts (MongoDB)?

    Stop on first error—unordered continues for independent docs.

    Example code

    // MongoDB: ordered inserts
    db.runCommand({ ping: 1 })
  72. Question 72

    What is write conflict retry (MongoDB)?

    Transactions abort on conflict—exponential backoff in app.

    Example code

    // MongoDB: write conflict retry
    db.runCommand({ ping: 1 })
  73. Question 73

    What is snapshot read concern (MongoDB)?

    Multi-doc consistent reads in transactions—compatibility matrix per version.

    Example code

    // MongoDB: snapshot read concern
    db.runCommand({ ping: 1 })
  74. Question 74

    What is causal consistency (MongoDB)?

    Session token ties reads after writes—driver session APIs.

    Example code

    // MongoDB: causal consistency
    db.runCommand({ ping: 1 })
  75. Question 75

    What is linearizable reads (MongoDB)?

    Strongest single-doc read—primary only and after write majority.

    Example code

    // MongoDB: linearizable reads
    db.runCommand({ ping: 1 })
  76. Question 76

    What is shard key hashed (MongoDB)?

    Hashed shard key spreads writes—loses range query locality.

    Example code

    // MongoDB: shard key hashed
    db.runCommand({ ping: 1 })
  77. Question 77

    What is shard key range (MongoDB)?

    Compound range keys—risk hot shard on monotonic inserts (e.g., time only).

    Example code

    // MongoDB: shard key range
    db.runCommand({ ping: 1 })
  78. Question 78

    What is refineCollectionShardKey (MongoDB)?

    Add suffix to shard key to split jumbo—planning migration carefully.

    Example code

    // MongoDB: refineCollectionShardKey
    db.runCommand({ ping: 1 })
  79. Question 79

    What is zone sharding (MongoDB)?

    Pin ranges to regions—data residency compliance patterns.

    Example code

    // MongoDB: zone sharding
    db.runCommand({ ping: 1 })
  80. Question 80

    What is moveChunk / balancer window (MongoDB)?

    Schedule balancing off-peak—throttle impact.

    Example code

    // MongoDB: moveChunk / balancer window
    db.runCommand({ ping: 1 })
  81. Question 81

    What is config servers (MongoDB)?

    Replica set holding chunk metadata—critical SPOF class; always HA.

    Example code

    // MongoDB: config servers
    db.runCommand({ ping: 1 })
  82. Question 82

    What is mongos caching (MongoDB)?

    Metadata refresh—stale router rare issues after sudden moves.

    Example code

    // MongoDB: mongos caching
    db.runCommand({ ping: 1 })
  83. Question 83

    What is reshardCollection (MongoDB)?

    Online shard key change (newer versions)—heavy operation; read docs.

    Example code

    // MongoDB: reshardCollection
    db.runCommand({ ping: 1 })
  84. Question 84

    What is Queryable Encryption (MongoDB)?

    Client-side encrypted fields with server-side queries—driver and version requirements.

    Example code

    // MongoDB: Queryable Encryption
    db.runCommand({ ping: 1 })
  85. Question 85

    What is Client-Side Field Level Encryption (MongoDB)?

    App encrypts selected fields—server never sees plaintext.

    Example code

    // MongoDB: Client-Side Field Level Encryption
    db.runCommand({ ping: 1 })
  86. Question 86

    What is LDAP/Kerberos (MongoDB)?

    Enterprise auth integrations—Ops/Atlas configuration.

    Example code

    // MongoDB: LDAP/Kerberos
    db.runCommand({ ping: 1 })
  87. Question 87

    What is Auditing (MongoDB)?

    Log DDL/DML to syslog/files—compliance; volume planning.

    Example code

    // MongoDB: Auditing
    db.runCommand({ ping: 1 })
  88. Question 88

    What is KMIP (MongoDB)?

    Key management integration—enterprise encryption at rest stories.

    Example code

    // MongoDB: KMIP
    db.runCommand({ ping: 1 })
  89. Question 89

    What is driver connection pools (MongoDB)?

    Size per process * pod count—avoid overwhelming mongos/mongod.

    Example code

    // MongoDB: driver connection pools
    db.runCommand({ ping: 1 })
  90. Question 90

    What is ServerSelectionTimeout (MongoDB)?

    Fail fast when no suitable member—tune for cloud blips.

    Example code

    // MongoDB: ServerSelectionTimeout
    db.runCommand({ ping: 1 })
  91. Question 91

    What is SRV connection string (MongoDB)?

    DNS seed list—SRV + TXT for TLS and replica set discovery.

    Example code

    // MongoDB: SRV connection string
    db.runCommand({ ping: 1 })
  92. Question 92

    What is Docker mongodb (MongoDB)?

    Stateful volume for /data/db—ulimits and transparent huge pages Linux tuning.

    Example code

    // MongoDB: Docker mongodb
    db.runCommand({ ping: 1 })
  93. Question 93

    What is Kubernetes operator (MongoDB)?

    Percona/MongoDB operators—StatefulSet patterns for replica sets.

    Example code

    // MongoDB: Kubernetes operator
    db.runCommand({ ping: 1 })
  94. Question 94

    What is mongotop (MongoDB)?

    Per-collection lock and time stats—pair with mongostat.

    Example code

    // MongoDB: mongotop
    db.runCommand({ ping: 1 })
  95. Question 95

    What is mongoreplay (MongoDB)?

    Replay captured traffic—capacity testing tool.

    Example code

    // MongoDB: mongoreplay
    db.runCommand({ ping: 1 })
  96. Question 96

    What is HTTP health check (MongoDB)?

    isMaster/hello for load balancers—driver compatibility with hello ok.

    Example code

    // MongoDB: HTTP health check
    db.runCommand({ ping: 1 })
  97. Question 97

    What is maxIncomingConnections (MongoDB)?

    Cap connections at mongod—align with load balancer limits.

    Example code

    // MongoDB: maxIncomingConnections
    db.runCommand({ ping: 1 })
  98. Question 98

    What is setParameter (MongoDB)?

    Runtime tunables—use cautiously in prod with change management.

    Example code

    // MongoDB: setParameter
    db.runCommand({ ping: 1 })
  99. Question 99

    What is tcmalloc tuning (MongoDB)?

    WiredTiger + glibc allocator interactions—Linux hugepages guidance in docs.

    Example code

    // MongoDB: tcmalloc tuning
    db.runCommand({ ping: 1 })
  100. Question 100

    What is traffic recording (MongoDB)?

    Capture subset of ops for support—privacy scrub fields.

    Example code

    // MongoDB: traffic recording
    db.runCommand({ ping: 1 })
  101. Question 101

    What is initial sync (MongoDB)?

    Replica full data copy—bandwidth and oplog window must suffice.

    Example code

    // MongoDB: initial sync
    db.runCommand({ ping: 1 })
  102. Question 102

    What is priority 0 member (MongoDB)?

    Secondary that never becomes primary—analytics or DR-only nodes.

    Example code

    // MongoDB: priority 0 member
    db.runCommand({ ping: 1 })