Back to interview questions

100+ MongoDB Interview Questions and Answers

100+ MongoDB Interview Questions and Answers

Explore 120 MongoDB interview questions and answers on BSON, queries, aggregation, indexes, transactions, replication, sharding, security and recovery.

Explore 120 MongoDB interview questions and answers on BSON, queries, aggregation, indexes, transactions, replication, sharding, security and recovery.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

MongoDB interviews should reveal whether a candidate can design documents around an application’s access patterns and preserve correctness as data, traffic and operational demands grow. Writing a query is only part of the job: array semantics, index choices, concurrent updates and failure handling can change both the result and its cost. Recruiters should ask candidates to connect each design choice to a concrete workload.

These 100+ MongoDB Interview Questions and Answers cover 120 questions across beginner, intermediate and experienced levels. They progress from BSON, document modeling and CRUD operations to aggregation, indexes, transactions, replication and sharding. Security and recovery questions assess how candidates would operate the database responsibly as well as develop against it.

How can recruiters distinguish practical MongoDB judgment from memorized query syntax?

Give the candidate a small set of documents and ask for the exact result of a query or update. Then introduce a missing field, multiple matching array elements or a concurrent writer. Strong candidates explain the resulting documents, the relevant atomicity boundary and how they would inspect the query plan or verify recovery before making a production decision.

Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation and unauthorized assistance during remote interviews. Pair those signals with document walkthroughs and follow-up questions about query behavior, index trade-offs and uncertain write outcomes. Treat signals as context for a fair review alongside demonstrated understanding, rather than conclusive proof of misconduct.

MongoDB Interview Questions

Choose questions that match the role’s development and operational responsibilities. Ask candidates to state document shapes, deployment topology and consistency requirements before proposing a solution. The complete question bank appears first, followed by identically numbered answers.

MongoDB Interview Questions for Beginners

Check whether candidates understand documents, BSON types and the exact effects of common operations. Small datasets expose misunderstandings about missing fields, arrays and update behavior.

  1. When is a document database such as MongoDB useful?

  2. How do a database, collection and document relate?

  3. How does BSON differ from ordinary JSON?

  4. What does _id identify, and is ObjectId a global sequence?

  5. How should you represent exact monetary values?

  6. How does a missing field differ from a field set to null?

  7. When should related data be embedded rather than referenced?

  8. Why should arrays be bounded in a document model?

  9. Does schema flexibility mean MongoDB does not need validation?

  10. What does single-document atomicity guarantee?

  11. How do insertOne and insertMany differ?

  12. How do a find filter and projection serve different purposes?

  13. How are comparison and logical conditions combined in a MongoDB filter?

  14. Why should a sort include a unique tie-breaker?

  15. What is a cursor, and how does limit affect a query?

  16. How does dot notation query a nested field?

  17. How does a scalar equality filter match an array field?

  18. Why use $elemMatch for several conditions on one array element?

  19. How does an array projection differ from filtering the document?

  20. How does an operator update differ from replacing a document?

  21. Why use $inc instead of reading a counter and writing a new value?

  22. How does $unset differ from assigning null?

  23. What does upsert do, and why can it need a unique index?

  24. What does updateMany guarantee, and what do its counts mean?

  25. How do deleteOne and deleteMany differ?

  26. What does findOneAndUpdate return?

  27. Why do indexes help queries, and what do they cost?

  28. Why does field order matter in a compound index?

  29. How does a unique single-field index handle missing and null values?

  30. What is a multikey index?

  31. What does an aggregation pipeline do?

  32. How do $match and $project differ in an aggregation?

  33. How do you count and sum within groups?

  34. How does $unwind affect empty or missing arrays?

  35. What does a basic $lookup add to each document?

  36. How should BSON dates and time zones be handled?

  37. How does mongosh differ from an application driver?

  38. What roles do primary and secondary members play in a replica set?

  39. How does sharding differ from replication?

  40. How does MongoDB Atlas differ from a self-managed deployment?

MongoDB Interview Questions for Intermediate

Explore schema evolution, index design, aggregation and application consistency. Ask what a proposed change does to both returned data and concurrent operations.

  1. How do access patterns guide a MongoDB document design?

  2. How would you prevent an embedded array from growing into an oversized document?

  3. How can JSON Schema validation enforce a useful document contract?

  4. How would you evolve a field without breaking older documents and applications?

  5. How does a version predicate prevent a lost update?

  6. How do arrayFilters update selected elements inside a document?

  7. When can the positional dollar operator update the wrong array element?

  8. When is an aggregation pipeline useful inside an update?

  9. How do ordered and unordered bulk writes behave when one operation fails?

  10. How would you implement stable range pagination for a sorted result?

  11. Why can an anchored regular expression use an index more effectively?

  12. Why might a query with collation fail to use the expected string index?

  13. When can a query use a partial index?

  14. How do sparse and partial unique indexes handle optional identifiers differently?

  15. Why should an application still check expiry when it uses a TTL index?

  16. What makes a query covered by an index?

  17. How do you choose between equality-sort-range and equality-range-sort index ordering?

  18. What should you inspect in explain executionStats beyond the winning plan name?

  19. How should you handle an aggregation sort that needs substantial memory?

  20. How can pipeline stage order change both performance and meaning?

  21. How do you keep a facet aggregation from building an oversized result?

  22. What determines whether a correlated lookup can use a foreign index?

  23. How can setWindowFields calculate a running total without collapsing rows?

  24. Why does dateTrunc need an explicit timezone for business-day reporting?

  25. How should you preserve decimal meaning in monetary calculations?

  26. Does unionWith remove duplicate records from combined collections?

  27. What must you decide before materializing aggregation output with merge?

  28. Why must every operation in a transaction use the same session?

  29. How do local, majority and snapshot read concerns differ in application behavior?

  30. How do write concern and journaling answer different durability questions?

  31. Why can a secondary read return an older value after a successful write?

  32. What conditions provide the full causal guarantees of a session?

  33. What do retryable writes protect against, and what do they not cover?

  34. How should transaction recovery distinguish a transient error from an uncertain commit?

  35. How should a change-stream consumer persist its resume position?

  36. How do connection-pool waits differ from server-selection and operation timeouts?

  37. How would you limit a MongoDB application account to its actual work?

  38. Why are TLS, authentication and authorization separate MongoDB controls?

  39. What makes a MongoDB backup suitable for a consistent restore?

  40. How can slow-query diagnostics expose sensitive information?

MongoDB Interview Questions for Experienced

Probe distributed behavior, performance diagnosis and recoverability. Ask candidates to identify an uncertain outcome, an operational boundary and the evidence needed to make a safe decision.

  1. How would you evaluate shard-key cardinality and value frequency together?

  2. When does a monotonically increasing shard key create a hotspot?

  3. How do you diagnose unexpected scatter-gather queries?

  4. What do zones guarantee, and what locality problems remain?

  5. What makes a resharding plan operationally credible?

  6. How does refining a shard key differ from resharding?

  7. How do unique indexes constrain a sharded data model?

  8. Why can migration and orphan documents complicate reads?

  9. Why might a balancer fail to resolve a badly skewed collection?

  10. How can a successful-looking write disappear after an election?

  11. How do replication lag and the oplog window interact during recovery?

  12. What should a change-stream consumer do when it cannot resume?

  13. Why should transaction callbacks avoid irreversible external effects?

  14. Why can a long-running transaction fail despite low request throughput?

  15. When would you avoid a cross-shard transaction?

  16. How would you design a distributed counter with a clear consistency contract?

  17. How would you investigate a query-plan regression affecting only some tenants?

  18. What can a hidden-index experiment prove?

  19. Why can a compound multikey index fail to combine expected bounds?

  20. How can a lookup pipeline unexpectedly multiply totals?

  21. How does time-series bucketing influence schema design?

  22. How should you reason about time-series expiration and corrections in MongoDB 8.0?

  23. When is a wildcard index a useful compromise?

  24. How do you distinguish a core text index from MongoDB Search?

  25. What must be established before choosing MongoDB Vector Search?

  26. What threat boundaries remain with Queryable Encryption?

  27. How do encrypted-field query restrictions affect data modeling?

  28. How would you choose between shared and isolated tenant storage?

  29. How do you investigate a hot tenant without blaming the shard count?

  30. What evidence proves that point-in-time recovery is usable?

  31. Why separate a binary upgrade from raising feature compatibility version?

  32. Why is downgrade planning different from rolling back an application release?

  33. How do you prevent a connection storm after a service restart?

  34. How do WiredTiger cache and operating-system memory interact?

  35. Why can storage grow much faster than logical document size?

  36. How do server time limits differ from client timeouts for uncertain writes?

  37. How does an outbox help connect MongoDB transactions to external delivery?

  38. How should deletion, retention and legal holds interact operationally?

  39. Does change-stream updateLookup return the document exactly as it was after that event?

  40. What evidence should you capture before mitigating a MongoDB incident?

MongoDB Interview Questions and Answers

The baseline is MongoDB Server 8.0, with later-version or deployment-specific behavior identified where relevant. Examples labeled mongosh JavaScript use MongoDB shell methods and BSON helpers, which differ from ordinary JavaScript and language-driver APIs. Treat fixture collections as disposable examples in an isolated test database; adapt schema, permissions and topology deliberately.

MongoDB Interview Questions and Answers for Beginners

These answers establish MongoDB’s document and query model, with explicit examples and the limits of common defaults.

1. When is a document database such as MongoDB useful?

MongoDB stores records as documents that can contain nested objects and arrays. It can fit applications whose frequently accessed data forms an aggregate, such as a product with its current descriptive attributes. Model the data around access and update patterns rather than selecting it simply to avoid tables.

For example, a product page can read a document containing its name and bounded specifications. A continuously growing history or relationship shared by many documents may need a separate collection. Document storage does not remove decisions about validation, indexes or consistency, and it does not make every relational workload a good fit without redesign.

2. How do a database, collection and document relate?

A database contains collections, and a collection stores documents. A document contains field-value pairs, where values can include nested documents, arrays and BSON-specific types. A collection provides a common operational and indexing boundary without requiring every document to contain identical fields.

For an inventory application, the database might contain products and suppliers collections. Each product document represents one product according to the chosen model. Decide what one document represents before adding fields: a collection that mixes unrelated entities without a clear discriminator and validation rules becomes difficult to query and maintain.

3. How does BSON differ from ordinary JSON?

BSON is MongoDB’s binary document representation and supports types beyond ordinary JSON, including dates, ObjectIds and several numeric representations. JSON text alone cannot preserve every BSON distinction without an agreed encoding such as Extended JSON.

For example, a quoted date string and a BSON Date may look similar in a display but behave differently in queries. Likewise, the number visible in a JSON export may not communicate whether the original value was a decimal or a 64-bit integer. Use the driver’s BSON handling or Extended JSON when preserving those distinctions matters.

4. What does _id identify, and is ObjectId a global sequence?

For an ordinary collection, _id identifies a document and is immutable. MongoDB normally creates a unique index on it. An ObjectId is a commonly generated identifier, but it is not a gap-free global sequence and should not be used as an exact ordering of all events across clients.

ObjectIds include a timestamp component with limited granularity, and generation can occur on different clients. If the application needs a business event time, store an explicit timestamp. If it needs ordering, define the ordering contract and a tie-breaker rather than assuming ObjectId order proves the exact time of an action. Sharded deployments also require attention to the documented scope of uniqueness enforcement.

5. How should you represent exact monetary values?

Choose a representation whose precision matches the monetary contract, such as BSON Decimal128 or an integer count of minor currency units. Binary floating-point values can introduce representation differences that are undesirable for exact decimal amounts. Currency and rounding rules remain part of the application model.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q05");
c.deleteMany({});
c.insertMany([{ _id: 1, amount: NumberDecimal("12.34"), currency: "USD" }]);
const result = c.findOne({ _id: 1 }).amount.toString();
printjson(result);
const c = db.getCollection("batch20261102_beginner_q05");
c.deleteMany({});
c.insertMany([{ _id: 1, amount: NumberDecimal("12.34"), currency: "USD" }]);
const result = c.findOne({ _id: 1 }).amount.toString();
printjson(result);
const c = db.getCollection("batch20261102_beginner_q05");
c.deleteMany({});
c.insertMany([{ _id: 1, amount: NumberDecimal("12.34"), currency: "USD" }]);
const result = c.findOne({ _id: 1 }).amount.toString();
printjson(result);

This stores a Decimal128 value created from a string and returns "12.34". Starting from the string avoids first converting the amount through a JavaScript binary floating-point value. Decimal128 does not decide tax rounding or currency conversion rules for you.

6. How does a missing field differ from a field set to null?

A missing field is absent from a document; a null field exists with a null value. MongoDB’s equality filter { field: null } matches both cases. Use an existence or type condition when the distinction matters to the query.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q06");
c.deleteMany({});
c.insertMany([{ _id: 1, note: null }, { _id: 2 }, { _id: 3, note: "ready" }]);
const ids = filter => c.find(filter).sort({ _id: 1 }).toArray().map(d => d._id);
const result = { equalNull: ids({ note: null }), missing: ids({ note: { $exists: false } }), bsonNull: ids({ note: { $type: 10 } }) };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q06");
c.deleteMany({});
c.insertMany([{ _id: 1, note: null }, { _id: 2 }, { _id: 3, note: "ready" }]);
const ids = filter => c.find(filter).sort({ _id: 1 }).toArray().map(d => d._id);
const result = { equalNull: ids({ note: null }), missing: ids({ note: { $exists: false } }), bsonNull: ids({ note: { $type: 10 } }) };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q06");
c.deleteMany({});
c.insertMany([{ _id: 1, note: null }, { _id: 2 }, { _id: 3, note: "ready" }]);
const ids = filter => c.find(filter).sort({ _id: 1 }).toArray().map(d => d._id);
const result = { equalNull: ids({ note: null }), missing: ids({ note: { $exists: false } }), bsonNull: ids({ note: { $type: 10 } }) };
printjson(result);

The three result arrays are [1,2] for equality to null, [2] for a missing field and [1] for BSON null. A business rule such as “not supplied” should specify whether explicit null belongs in the same category.

7. When should related data be embedded rather than referenced?

Embed related data when it belongs to the same aggregate and is commonly read or changed together, provided its size remains controlled. References keep related entities in separate documents and can be appropriate for independently changing or widely shared data. Neither choice is universally faster or more correct.

An order can embed the purchased item descriptions and agreed prices as a historical snapshot, while referring to a separately maintained customer. Updating a current product description should not silently rewrite the historical sale. Consider duplication, update frequency and the consistency needed when deciding which information is a snapshot and which is a live relationship.

8. Why should arrays be bounded in a document model?

An array that grows indefinitely can make a document expensive to read and update and eventually exceed MongoDB’s document-size limit. The BSON document limit is 16 MiB, but practical performance or contention limits may matter earlier. Define expected growth rather than assuming nested data is always cheap.

A document holding a short list of product tags is different from a customer document accumulating every lifetime event. A separate event collection with an indexed customer reference can support independent retention and querying. If recent items are embedded for convenience, define how many are retained and where the complete history lives.

9. Does schema flexibility mean MongoDB does not need validation?

Schema flexibility permits documents with different shapes; it does not make all shapes desirable. Collection validation can enforce selected requirements, including types and required fields, while still allowing deliberate variation. Application validation and database validation can serve complementary purposes.

If some producers send a quantity as a number and others as text, sorting and aggregation can become misleading. A validator can reject incompatible writes according to its configured action and level. Decide how existing documents and schema changes will be handled rather than adding strict rules without checking the collection’s current data.

10. What does single-document atomicity guarantee?

An update to one document is atomic even when it changes several fields. This does not automatically make a multi-document workflow atomic. A filter can also include an expected current value so an update applies only when the document still satisfies that condition.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q10");
c.deleteMany({});
c.insertMany([{ _id: 1, quantity: 5 }]);
const first = c.updateOne({ _id: 1, quantity: 5 }, { $set: { quantity: 4 } });
const second = c.updateOne({ _id: 1, quantity: 5 }, { $set: { quantity: 3 } });
const result = [first.matchedCount, second.matchedCount];
printjson(result);
const c = db.getCollection("batch20261102_beginner_q10");
c.deleteMany({});
c.insertMany([{ _id: 1, quantity: 5 }]);
const first = c.updateOne({ _id: 1, quantity: 5 }, { $set: { quantity: 4 } });
const second = c.updateOne({ _id: 1, quantity: 5 }, { $set: { quantity: 3 } });
const result = [first.matchedCount, second.matchedCount];
printjson(result);
const c = db.getCollection("batch20261102_beginner_q10");
c.deleteMany({});
c.insertMany([{ _id: 1, quantity: 5 }]);
const first = c.updateOne({ _id: 1, quantity: 5 }, { $set: { quantity: 4 } });
const second = c.updateOne({ _id: 1, quantity: 5 }, { $set: { quantity: 3 } });
const result = [first.matchedCount, second.matchedCount];
printjson(result);

The first conditional update changes the quantity from 5 to 4. The second matches nothing because quantity is no longer 5, producing matched counts [1,0]. This demonstrates conditional matching sequentially; it is not a concurrent stress test.

11. How do insertOne and insertMany differ?

insertOne inserts one document; insertMany submits several and reports their inserted identifiers. Explicit identifiers make small fixtures predictable, while applications often use generated identifiers. An insert is not an update of an existing document with the same _id.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q11");
c.deleteMany({});
c.insertOne({ _id: 1, name: "A" });
c.insertMany([{ _id: 2, name: "B" }, { _id: 3, name: "C" }]);
const result = c.find().sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q11");
c.deleteMany({});
c.insertOne({ _id: 1, name: "A" });
c.insertMany([{ _id: 2, name: "B" }, { _id: 3, name: "C" }]);
const result = c.find().sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q11");
c.deleteMany({});
c.insertOne({ _id: 1, name: "A" });
c.insertMany([{ _id: 2, name: "B" }, { _id: 3, name: "C" }]);
const result = c.find().sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);

This fixture ends with IDs [1,2,3]. In a batch, ordered insertion normally stops at the first write error, but earlier successful writes are not automatically rolled back. Unordered insertion can continue with other writes; neither mode by itself turns the entire batch into an all-or-nothing transaction.

12. How do a find filter and projection serve different purposes?

The filter chooses matching documents, while the projection controls which fields are returned. Restricting the output can reduce unnecessary data transfer and clarify the result contract. Inclusion and exclusion projections generally cannot be mixed, with the special allowance for excluding _id.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q12");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }, { _id: 2, name: "B", quantity: 0 }]);
const result = c.find({ quantity: { $gt: 0 } }, { _id: 0, name: 1 }).sort({ name: 1 }).toArray();
printjson(result);
const c = db.getCollection("batch20261102_beginner_q12");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }, { _id: 2, name: "B", quantity: 0 }]);
const result = c.find({ quantity: { $gt: 0 } }, { _id: 0, name: 1 }).sort({ name: 1 }).toArray();
printjson(result);
const c = db.getCollection("batch20261102_beginner_q12");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }, { _id: 2, name: "B", quantity: 0 }]);
const result = c.find({ quantity: { $gt: 0 } }, { _id: 0, name: 1 }).sort({ name: 1 }).toArray();
printjson(result);

The result is one document, { name: "A" }. The quantity determines whether the record matches but is not returned. A projection does not change the stored document, and hiding a field in one query does not replace authorization controls.

13. How are comparison and logical conditions combined in a MongoDB filter?

Comparison operators such as $gte constrain field values. Conditions on different fields in the same filter are combined with an implicit AND; operators such as $or express alternatives. Write the filter around the intended rule rather than relying on the order of object fields.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q13");
c.deleteMany({});
c.insertMany([{ _id: 1, active: true, score: 7 }, { _id: 2, active: false, score: 8 }, { _id: 3, active: true, score: 12 }]);
const result = c.find({ active: true, score: { $gte: 5, $lte: 10 } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q13");
c.deleteMany({});
c.insertMany([{ _id: 1, active: true, score: 7 }, { _id: 2, active: false, score: 8 }, { _id: 3, active: true, score: 12 }]);
const result = c.find({ active: true, score: { $gte: 5, $lte: 10 } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q13");
c.deleteMany({});
c.insertMany([{ _id: 1, active: true, score: 7 }, { _id: 2, active: false, score: 8 }, { _id: 3, active: true, score: 12 }]);
const result = c.find({ active: true, score: { $gte: 5, $lte: 10 } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);

Only ID 1 matches: it is active and has a score between 5 and 10 inclusive. Keep the compared values in compatible types and avoid duplicate keys in a JavaScript object, because a later duplicate can replace an earlier condition before the query reaches MongoDB.

14. Why should a sort include a unique tie-breaker?

Sorting by a nonunique field does not define the order among tied documents. Add a suitable unique tie-breaker when stable ordering matters, such as for a reproducible top result or pagination. A natural or insertion order should not be treated as a contractual result order.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q14");
c.deleteMany({});
c.insertMany([{ _id: 2, score: 9 }, { _id: 1, score: 9 }, { _id: 3, score: 4 }]);
const result = c.find().sort({ score: -1, _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q14");
c.deleteMany({});
c.insertMany([{ _id: 2, score: 9 }, { _id: 1, score: 9 }, { _id: 3, score: 4 }]);
const result = c.find().sort({ score: -1, _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q14");
c.deleteMany({});
c.insertMany([{ _id: 2, score: 9 }, { _id: 1, score: 9 }, { _id: 3, score: 4 }]);
const result = c.find().sort({ score: -1, _id: 1 }).toArray().map(d => d._id);
printjson(result);

The output IDs are [1,2,3]: score sorts descending, then ID ascending breaks the tie at score 9. The second key makes the intended order explicit; it is not necessary to pretend the two tied scores are different.

15. What is a cursor, and how does limit affect a query?

find returns a cursor for retrieving matching documents. A limit caps the number returned, while sorting defines which documents qualify as the first results. Converting the cursor to an array is convenient for a small fixture but collects its results in client memory.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q15");
c.deleteMany({});
c.insertMany([{ _id: 3 }, { _id: 1 }, { _id: 2 }]);
const result = c.find().sort({ _id: 1 }).limit(2).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q15");
c.deleteMany({});
c.insertMany([{ _id: 3 }, { _id: 1 }, { _id: 2 }]);
const result = c.find().sort({ _id: 1 }).limit(2).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q15");
c.deleteMany({});
c.insertMany([{ _id: 3 }, { _id: 1 }, { _id: 2 }]);
const result = c.find().sort({ _id: 1 }).limit(2).toArray().map(d => d._id);
printjson(result);

The result contains IDs [1,2]. Without a defined sort, “the first two” would not be a reliable business rule. For large results, use the driver’s cursor iteration appropriately rather than materializing the complete dataset solely because a small shell example uses toArray().

16. How does dot notation query a nested field?

Dot notation addresses a field inside an embedded document without requiring equality with the complete embedded object. It is useful when the query needs one nested attribute while other attributes can vary.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q16");
c.deleteMany({});
c.insertMany([{ _id: 1, address: { city: "Leeds", postal: "LS1" } }, { _id: 2, address: { city: "York", postal: "YO1" } }]);
const result = c.find({ "address.city": "Leeds" }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q16");
c.deleteMany({});
c.insertMany([{ _id: 1, address: { city: "Leeds", postal: "LS1" } }, { _id: 2, address: { city: "York", postal: "YO1" } }]);
const result = c.find({ "address.city": "Leeds" }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q16");
c.deleteMany({});
c.insertMany([{ _id: 1, address: { city: "Leeds", postal: "LS1" } }, { _id: 2, address: { city: "York", postal: "YO1" } }]);
const result = c.find({ "address.city": "Leeds" }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);

The output is [1]. The filter checks the city regardless of the postal code. Matching the entire address object instead introduces a different requirement involving its complete content and field order, so do not substitute whole-object equality for a nested-field question.

17. How does a scalar equality filter match an array field?

When an array field contains scalar values, a scalar equality condition can match a document containing that value as an array element. This differs from matching an entire array value, where the elements and order matter.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q17");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["blue", "sale"] }, { _id: 2, tags: [] }, { _id: 3, tags: ["blue"] }]);
const result = c.find({ tags: "blue" }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q17");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["blue", "sale"] }, { _id: 2, tags: [] }, { _id: 3, tags: ["blue"] }]);
const result = c.find({ tags: "blue" }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q17");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["blue", "sale"] }, { _id: 2, tags: [] }, { _id: 3, tags: ["blue"] }]);
const result = c.find({ tags: "blue" }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);

IDs [1,3] match because each tags array contains "blue". The empty array does not match. This result is a set of documents, not one output row per matching array element; use a deliberate expansion when a downstream analysis needs elements rather than documents.

18. Why use $elemMatch for several conditions on one array element?

$elemMatch requires a single array element to satisfy the enclosed conditions. Separate dotted conditions on an array of embedded documents can otherwise be satisfied by different elements, which may not express the intended rule.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q18");
c.deleteMany({});
c.insertMany([{ _id: 1, items: [{ color: "red", quantity: 1 }, { color: "blue", quantity: 5 }] }, { _id: 2, items: [{ color: "red", quantity: 5 }] }]);
const result = c.find({ items: { $elemMatch: { color: "red", quantity: { $gte: 5 } } } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q18");
c.deleteMany({});
c.insertMany([{ _id: 1, items: [{ color: "red", quantity: 1 }, { color: "blue", quantity: 5 }] }, { _id: 2, items: [{ color: "red", quantity: 5 }] }]);
const result = c.find({ items: { $elemMatch: { color: "red", quantity: { $gte: 5 } } } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q18");
c.deleteMany({});
c.insertMany([{ _id: 1, items: [{ color: "red", quantity: 1 }, { color: "blue", quantity: 5 }] }, { _id: 2, items: [{ color: "red", quantity: 5 }] }]);
const result = c.find({ items: { $elemMatch: { color: "red", quantity: { $gte: 5 } } } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);

ID 1 has a red item and a quantity of 5, but in different elements. Only ID 2 has one red item whose quantity is at least 5, so it is the sole result. This distinction prevents unrelated array elements from jointly satisfying a rule intended for one item.

19. How does an array projection differ from filtering the document?

A query filter selects documents, while an array projection limits which array content is returned. For example, projection $slice can return a bounded portion, and projection $elemMatch returns the first matching array element. Neither should be confused with returning every matching element.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q19");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["a", "b", "c"] }]);
const result = c.findOne({ _id: 1 }, { _id: 0, tags: { $slice: 2 } });
printjson(result);
const c = db.getCollection("batch20261102_beginner_q19");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["a", "b", "c"] }]);
const result = c.findOne({ _id: 1 }, { _id: 0, tags: { $slice: 2 } });
printjson(result);
const c = db.getCollection("batch20261102_beginner_q19");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["a", "b", "c"] }]);
const result = c.findOne({ _id: 1 }, { _id: 0, tags: { $slice: 2 } });
printjson(result);

The result has tags: ["a","b"]. The stored array still contains three elements. If the requirement is to return all elements meeting a condition, consider an appropriate aggregation expression rather than assuming a first-match projection performs that filtering.

20. How does an operator update differ from replacing a document?

An operator update changes specified fields using operators such as $set. A replacement supplies a new document body and removes ordinary fields that are not included, while preserving the immutable identity rules. Use the operation that matches the intended change.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q20");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }]);
c.updateOne({ _id: 1 }, { $set: { name: "B" } });
const afterUpdate = c.findOne({ _id: 1 });
c.replaceOne({ _id: 1 }, { name: "C" });
const result = { afterUpdate, afterReplacement: c.findOne({ _id: 1 }) };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q20");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }]);
c.updateOne({ _id: 1 }, { $set: { name: "B" } });
const afterUpdate = c.findOne({ _id: 1 });
c.replaceOne({ _id: 1 }, { name: "C" });
const result = { afterUpdate, afterReplacement: c.findOne({ _id: 1 }) };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q20");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }]);
c.updateOne({ _id: 1 }, { $set: { name: "B" } });
const afterUpdate = c.findOne({ _id: 1 });
c.replaceOne({ _id: 1 }, { name: "C" });
const result = { afterUpdate, afterReplacement: c.findOne({ _id: 1 }) };
printjson(result);

After the operator update, name is B and quantity remains 4. After replacement, the document has name C and no quantity field. The example makes the destructive difference visible: replacement is not shorthand for merging a few new values into the existing document.

21. Why use $inc instead of reading a counter and writing a new value?

$inc changes a numeric field on the server as part of an atomic single-document update. A client-side read, addition and later assignment can overwrite another client’s intervening change. The operation still needs an appropriate filter and a valid numeric field.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q21");
c.deleteMany({});
c.insertMany([{ _id: 1, count: 0 }]);
c.updateOne({ _id: 1 }, { $inc: { count: 2 } });
c.updateOne({ _id: 1 }, { $inc: { count: 3 } });
const result = c.findOne({ _id: 1 }).count;
printjson(result);
const c = db.getCollection("batch20261102_beginner_q21");
c.deleteMany({});
c.insertMany([{ _id: 1, count: 0 }]);
c.updateOne({ _id: 1 }, { $inc: { count: 2 } });
c.updateOne({ _id: 1 }, { $inc: { count: 3 } });
const result = c.findOne({ _id: 1 }).count;
printjson(result);
const c = db.getCollection("batch20261102_beginner_q21");
c.deleteMany({});
c.insertMany([{ _id: 1, count: 0 }]);
c.updateOne({ _id: 1 }, { $inc: { count: 2 } });
c.updateOne({ _id: 1 }, { $inc: { count: 3 } });
const result = c.findOne({ _id: 1 }).count;
printjson(result);

The counter finishes at 5 after increments of 2 and 3. This illustrates the arithmetic and update form, not a measured concurrent workload. Atomic increments do not provide a gap-free business-numbering system or eliminate every retry consideration.

22. How does $unset differ from assigning null?

$unset removes the named field. Assigning null with $set leaves the field present with a null value. That difference affects existence tests, validation rules and application code that distinguishes absent information from an explicit empty value.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q22");
c.deleteMany({});
c.insertMany([{ _id: 1, note: "old", status: "ready" }]);
c.updateOne({ _id: 1 }, { $unset: { note: "" }, $set: { status: null } });
const d = c.findOne({ _id: 1 });
const result = { noteExists: Object.prototype.hasOwnProperty.call(d, "note"), statusIsNull: d.status === null };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q22");
c.deleteMany({});
c.insertMany([{ _id: 1, note: "old", status: "ready" }]);
c.updateOne({ _id: 1 }, { $unset: { note: "" }, $set: { status: null } });
const d = c.findOne({ _id: 1 });
const result = { noteExists: Object.prototype.hasOwnProperty.call(d, "note"), statusIsNull: d.status === null };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q22");
c.deleteMany({});
c.insertMany([{ _id: 1, note: "old", status: "ready" }]);
c.updateOne({ _id: 1 }, { $unset: { note: "" }, $set: { status: null } });
const d = c.findOne({ _id: 1 });
const result = { noteExists: Object.prototype.hasOwnProperty.call(d, "note"), statusIsNull: d.status === null };
printjson(result);

The final result is { noteExists: false, statusIsNull: true }. An equality-to-null query alone would not demonstrate this distinction because it can match a missing field too. Choose the update according to the intended document contract.

23. What does upsert do, and why can it need a unique index?

With upsert: true, an update inserts a document when its filter finds no match. It is useful for a clearly identified entity, but concurrent operations using a nonunique business filter can otherwise create duplicate entities. Enforce the intended uniqueness in the database where appropriate.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q23");
c.deleteMany({});
c.createIndex({ code: 1 }, { unique: true });
c.updateOne({ code: "A" }, { $set: { quantity: 2 }, $setOnInsert: { _id: 1 } }, { upsert: true });
c.updateOne({ code: "A" }, { $set: { quantity: 4 }, $setOnInsert: { _id: 1 } }, { upsert: true });
const result = { count: c.countDocuments({}), quantity: c.findOne({ code: "A" }).quantity };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q23");
c.deleteMany({});
c.createIndex({ code: 1 }, { unique: true });
c.updateOne({ code: "A" }, { $set: { quantity: 2 }, $setOnInsert: { _id: 1 } }, { upsert: true });
c.updateOne({ code: "A" }, { $set: { quantity: 4 }, $setOnInsert: { _id: 1 } }, { upsert: true });
const result = { count: c.countDocuments({}), quantity: c.findOne({ code: "A" }).quantity };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q23");
c.deleteMany({});
c.createIndex({ code: 1 }, { unique: true });
c.updateOne({ code: "A" }, { $set: { quantity: 2 }, $setOnInsert: { _id: 1 } }, { upsert: true });
c.updateOne({ code: "A" }, { $set: { quantity: 4 }, $setOnInsert: { _id: 1 } }, { upsert: true });
const result = { count: c.countDocuments({}), quantity: c.findOne({ code: "A" }).quantity };
printjson(result);

Two sequential upserts for the indexed code produce one document with quantity 4. The unique index expresses the code’s uniqueness requirement; the example does not test concurrency or every duplicate-key retry path. $setOnInsert supplies values only when an insertion occurs.

24. What does updateMany guarantee, and what do its counts mean?

updateMany applies an update to matching documents. Each document update is atomic, but the entire set is not automatically one atomic transaction. matchedCount counts matches, while modifiedCount counts documents actually changed; those values need not be equal.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q24");
c.deleteMany({});
c.insertMany([{ _id: 1, team: "A", status: "ready" }, { _id: 2, team: "A", status: "new" }, { _id: 3, team: "B", status: "new" }]);
const r = c.updateMany({ team: "A" }, { $set: { status: "ready" } });
const result = { matched: r.matchedCount, modified: r.modifiedCount };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q24");
c.deleteMany({});
c.insertMany([{ _id: 1, team: "A", status: "ready" }, { _id: 2, team: "A", status: "new" }, { _id: 3, team: "B", status: "new" }]);
const r = c.updateMany({ team: "A" }, { $set: { status: "ready" } });
const result = { matched: r.matchedCount, modified: r.modifiedCount };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q24");
c.deleteMany({});
c.insertMany([{ _id: 1, team: "A", status: "ready" }, { _id: 2, team: "A", status: "new" }, { _id: 3, team: "B", status: "new" }]);
const r = c.updateMany({ team: "A" }, { $set: { status: "ready" } });
const result = { matched: r.matchedCount, modified: r.modifiedCount };
printjson(result);

The result has matched count 2 and modified count 1 because one matched document already had the target status. Check both the filter and these counts when validating a change. A successful bulk update does not imply that unrelated writers could not run between individual document updates.

25. How do deleteOne and deleteMany differ?

deleteOne removes at most one matching document, while deleteMany removes all documents matching its filter. If a particular document must be deleted, identify it explicitly rather than relying on an unspecified match among several candidates.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q25");
c.deleteMany({});
c.insertMany([{ _id: 1, archived: true }, { _id: 2, archived: true }, { _id: 3, archived: false }]);
const one = c.deleteOne({ _id: 1 });
const many = c.deleteMany({ archived: true });
const result = { deleted: [one.deletedCount, many.deletedCount], remaining: c.find().sort({ _id: 1 }).toArray().map(d => d._id) };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q25");
c.deleteMany({});
c.insertMany([{ _id: 1, archived: true }, { _id: 2, archived: true }, { _id: 3, archived: false }]);
const one = c.deleteOne({ _id: 1 });
const many = c.deleteMany({ archived: true });
const result = { deleted: [one.deletedCount, many.deletedCount], remaining: c.find().sort({ _id: 1 }).toArray().map(d => d._id) };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q25");
c.deleteMany({});
c.insertMany([{ _id: 1, archived: true }, { _id: 2, archived: true }, { _id: 3, archived: false }]);
const one = c.deleteOne({ _id: 1 });
const many = c.deleteMany({ archived: true });
const result = { deleted: [one.deletedCount, many.deletedCount], remaining: c.find().sort({ _id: 1 }).toArray().map(d => d._id) };
printjson(result);

The operations delete one identified document and then one remaining archived document, leaving ID 3. The initial empty-filter deletion is deliberately limited to this named practice collection; an empty filter against an application collection would target every document. Review the intended filter and scope before executing destructive operations.

26. What does findOneAndUpdate return?

findOneAndUpdate changes a matching document and returns a document according to its return option. In mongosh it returns the original document by default; returnDocument: "after" requests the updated document. Driver APIs can expose different option or result conventions, so use the documentation for the actual client.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q26");
c.deleteMany({});
c.insertMany([{ _id: 1, quantity: 2 }]);
const result = c.findOneAndUpdate({ _id: 1 }, { $inc: { quantity: 1 } }, { returnDocument: "after" });
printjson(result);
const c = db.getCollection("batch20261102_beginner_q26");
c.deleteMany({});
c.insertMany([{ _id: 1, quantity: 2 }]);
const result = c.findOneAndUpdate({ _id: 1 }, { $inc: { quantity: 1 } }, { returnDocument: "after" });
printjson(result);
const c = db.getCollection("batch20261102_beginner_q26");
c.deleteMany({});
c.insertMany([{ _id: 1, quantity: 2 }]);
const result = c.findOneAndUpdate({ _id: 1 }, { $inc: { quantity: 1 } }, { returnDocument: "after" });
printjson(result);

This returns the document with quantity 3 after incrementing from 2. It avoids a separate read solely to retrieve that operation’s updated result. A returned document does not make a larger workflow involving other documents atomic, and a filter that matches nothing needs explicit handling.

27. Why do indexes help queries, and what do they cost?

An index organizes selected field values so MongoDB can locate or order relevant documents without always scanning the complete collection. Indexes consume storage and memory and must be maintained when indexed data changes. Adding every possible index can therefore make writes and operations more expensive.

For a frequent lookup by product code, an appropriate index can reduce examined data. Whether it actually helps depends on selectivity, the query shape and the execution plan. Inspect representative query evidence rather than assuming an index exists because a query returned quickly on three test documents.

28. Why does field order matter in a compound index?

A compound index orders entries by its listed fields, so leading prefixes matter. An index on { region: 1, score: -1 } naturally supports access beginning with region and can support a compatible score order within a region. It is not interchangeable with an index beginning with score.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q28");
c.deleteMany({});
c.insertMany([{ _id: 1, region: "A", score: 3 }, { _id: 2, region: "A", score: 9 }, { _id: 3, region: "B", score: 8 }]);
c.createIndex({ region: 1, score: -1 });
const result = c.find({ region: "A" }).sort({ score: -1, _id: 1 }).toArray().map(d => d.score);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q28");
c.deleteMany({});
c.insertMany([{ _id: 1, region: "A", score: 3 }, { _id: 2, region: "A", score: 9 }, { _id: 3, region: "B", score: 8 }]);
c.createIndex({ region: 1, score: -1 });
const result = c.find({ region: "A" }).sort({ score: -1, _id: 1 }).toArray().map(d => d.score);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q28");
c.deleteMany({});
c.insertMany([{ _id: 1, region: "A", score: 3 }, { _id: 2, region: "A", score: 9 }, { _id: 3, region: "B", score: 8 }]);
c.createIndex({ region: 1, score: -1 });
const result = c.find({ region: "A" }).sort({ score: -1, _id: 1 }).toArray().map(d => d.score);
printjson(result);

The fixture returns region A’s scores as [9,3]. The result demonstrates the requested filter and order; it does not prove which plan the optimizer will choose for a tiny collection. Assess the actual query and explain output before generalizing performance claims.

29. How does a unique single-field index handle missing and null values?

For a conventional unique single-field index, a missing field is indexed as a null entry. Therefore only one document can occupy that null key, whether its field is missing or explicitly null. This differs from assuming every absent field is exempt from uniqueness.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q29");
c.deleteMany({});
c.createIndex({ externalCode: 1 }, { unique: true });
c.insertOne({ _id: 1 });
let duplicateCode = null;
try { c.insertOne({ _id: 2, externalCode: null }); }
catch (error) { duplicateCode = error.code; }
const result = { duplicateCode, count: c.countDocuments({}) };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q29");
c.deleteMany({});
c.createIndex({ externalCode: 1 }, { unique: true });
c.insertOne({ _id: 1 });
let duplicateCode = null;
try { c.insertOne({ _id: 2, externalCode: null }); }
catch (error) { duplicateCode = error.code; }
const result = { duplicateCode, count: c.countDocuments({}) };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q29");
c.deleteMany({});
c.createIndex({ externalCode: 1 }, { unique: true });
c.insertOne({ _id: 1 });
let duplicateCode = null;
try { c.insertOne({ _id: 2, externalCode: null }); }
catch (error) { duplicateCode = error.code; }
const result = { duplicateCode, count: c.countDocuments({}) };
printjson(result);

The second insertion fails with duplicate-key code 11000, and one document remains. Partial and sparse index designs have their own semantics and should be chosen deliberately when only certain documents must participate in uniqueness. This fixture illustrates the ordinary unique-index case.

30. What is a multikey index?

MongoDB automatically makes an index multikey when it indexes an array field, allowing array values to support queries. One document can contribute multiple index entries. That is different from expanding the document into several independent stored documents.

An index on tags can help find documents containing a specified tag, but array indexes have restrictions, including compound-index limitations involving multiple array fields in one document. Do not assume every scalar compound-index design transfers unchanged to arrays. Also consider how large or frequently changed arrays affect index maintenance.

31. What does an aggregation pipeline do?

An aggregation pipeline passes documents through ordered stages that can filter, reshape, group or combine data. Each stage receives the preceding stage’s output, so changes in shape and row count matter. Ordinary read pipelines do not modify the source collection unless a writing stage such as $merge or $out is used.

For a sales summary, the pipeline might filter the relevant period, group by region and sort the summaries. Sorting before grouping does not automatically make the grouped output sorted. Explain what one document represents after each stage rather than treating the pipeline as a list of independent operations.

32. How do $match and $project differ in an aggregation?

$match chooses documents according to a condition, while $project reshapes the fields passed onward and can compute expressions. Their order affects which fields are available for later stages. Push useful filtering early where appropriate, while respecting dependencies on computed values.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q32");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }, { _id: 2, name: "B", quantity: 0 }]);
const result = c.aggregate([{ $match: { quantity: { $gt: 0 } } }, { $project: { _id: 0, name: 1, doubled: { $multiply: ["$quantity", 2] } } }]).toArray();
printjson(result);
const c = db.getCollection("batch20261102_beginner_q32");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }, { _id: 2, name: "B", quantity: 0 }]);
const result = c.aggregate([{ $match: { quantity: { $gt: 0 } } }, { $project: { _id: 0, name: 1, doubled: { $multiply: ["$quantity", 2] } } }]).toArray();
printjson(result);
const c = db.getCollection("batch20261102_beginner_q32");
c.deleteMany({});
c.insertMany([{ _id: 1, name: "A", quantity: 4 }, { _id: 2, name: "B", quantity: 0 }]);
const result = c.aggregate([{ $match: { quantity: { $gt: 0 } } }, { $project: { _id: 0, name: 1, doubled: { $multiply: ["$quantity", 2] } } }]).toArray();
printjson(result);

The result is { name: "A", doubled: 8 }. The source field quantity is used in the calculation but not retained in the projected output. A later stage cannot use that removed field as though the document still had its original shape.

33. How do you count and sum within groups?

$group defines groups through its _id expression and uses accumulators for measures. $sum: 1 counts input documents in each group, while summing a field adds its qualifying numeric values. The output grain becomes one document per group key.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q33");
c.deleteMany({});
c.insertMany([{ _id: 1, region: "A", units: 2 }, { _id: 2, region: "A", units: 5 }, { _id: 3, region: "B", units: 6 }]);
const result = c.aggregate([{ $group: { _id: "$region", records: { $sum: 1 }, units: { $sum: "$units" } } }, { $sort: { _id: 1 } }]).toArray();
printjson(result);
const c = db.getCollection("batch20261102_beginner_q33");
c.deleteMany({});
c.insertMany([{ _id: 1, region: "A", units: 2 }, { _id: 2, region: "A", units: 5 }, { _id: 3, region: "B", units: 6 }]);
const result = c.aggregate([{ $group: { _id: "$region", records: { $sum: 1 }, units: { $sum: "$units" } } }, { $sort: { _id: 1 } }]).toArray();
printjson(result);
const c = db.getCollection("batch20261102_beginner_q33");
c.deleteMany({});
c.insertMany([{ _id: 1, region: "A", units: 2 }, { _id: 2, region: "A", units: 5 }, { _id: 3, region: "B", units: 6 }]);
const result = c.aggregate([{ $group: { _id: "$region", records: { $sum: 1 }, units: { $sum: "$units" } } }, { $sort: { _id: 1 } }]).toArray();
printjson(result);

Region A has two documents totaling 7 units; region B has one totaling 6. The explicit final sort makes the example’s output order predictable. Check source types and missing-value rules before interpreting a numeric total, because a grouping stage does not validate the business quality of every input.

34. How does $unwind affect empty or missing arrays?

$unwind emits an output document for each array element. By default, null, missing and empty-array cases do not produce an output document. preserveNullAndEmptyArrays: true retains those cases when their parent documents should remain in the analysis.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q34");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["a", "b"] }, { _id: 2, tags: [] }, { _id: 3 }, { _id: 4, tags: null }]);
const expanded = c.aggregate([{ $unwind: "$tags" }]).toArray();
const preserved = c.aggregate([{ $unwind: { path: "$tags", preserveNullAndEmptyArrays: true } }]).toArray();
const result = { expanded: expanded.length, preserved: preserved.length };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q34");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["a", "b"] }, { _id: 2, tags: [] }, { _id: 3 }, { _id: 4, tags: null }]);
const expanded = c.aggregate([{ $unwind: "$tags" }]).toArray();
const preserved = c.aggregate([{ $unwind: { path: "$tags", preserveNullAndEmptyArrays: true } }]).toArray();
const result = { expanded: expanded.length, preserved: preserved.length };
printjson(result);
const c = db.getCollection("batch20261102_beginner_q34");
c.deleteMany({});
c.insertMany([{ _id: 1, tags: ["a", "b"] }, { _id: 2, tags: [] }, { _id: 3 }, { _id: 4, tags: null }]);
const expanded = c.aggregate([{ $unwind: "$tags" }]).toArray();
const preserved = c.aggregate([{ $unwind: { path: "$tags", preserveNullAndEmptyArrays: true } }]).toArray();
const result = { expanded: expanded.length, preserved: preserved.length };
printjson(result);

The default expansion produces 2 rows from the two tags on ID 1. Preserving empty, missing and null cases produces 5 rows overall. This can change totals dramatically, so decide whether the metric counts parent documents or expanded elements before grouping the result.

35. What does a basic $lookup add to each document?

$lookup can match a local field against a foreign collection’s field and add an array of matching documents. A missing match produces an empty array in this basic form, while multiple matches can produce several elements. It does not automatically flatten those elements or enforce a foreign-key constraint.

mongosh JavaScript

const orders = db.getCollection("batch20261102_beginner_q35_orders");
const customers = db.getCollection("batch20261102_beginner_q35_customers");
orders.deleteMany({});
customers.deleteMany({});
customers.insertOne({ _id: 10, name: "Mira" });
orders.insertMany([{ _id: 1, customerId: 10 }, { _id: 2, customerId: 99 }]);
const result = orders.aggregate([{ $lookup: { from: "batch20261102_beginner_q35_customers", localField: "customerId", foreignField: "_id", as: "customer" } }, { $sort: { _id: 1 } }, { $project: { _id: 1, names: "$customer.name" } }]).toArray();
printjson(result);
const orders = db.getCollection("batch20261102_beginner_q35_orders");
const customers = db.getCollection("batch20261102_beginner_q35_customers");
orders.deleteMany({});
customers.deleteMany({});
customers.insertOne({ _id: 10, name: "Mira" });
orders.insertMany([{ _id: 1, customerId: 10 }, { _id: 2, customerId: 99 }]);
const result = orders.aggregate([{ $lookup: { from: "batch20261102_beginner_q35_customers", localField: "customerId", foreignField: "_id", as: "customer" } }, { $sort: { _id: 1 } }, { $project: { _id: 1, names: "$customer.name" } }]).toArray();
printjson(result);
const orders = db.getCollection("batch20261102_beginner_q35_orders");
const customers = db.getCollection("batch20261102_beginner_q35_customers");
orders.deleteMany({});
customers.deleteMany({});
customers.insertOne({ _id: 10, name: "Mira" });
orders.insertMany([{ _id: 1, customerId: 10 }, { _id: 2, customerId: 99 }]);
const result = orders.aggregate([{ $lookup: { from: "batch20261102_beginner_q35_customers", localField: "customerId", foreignField: "_id", as: "customer" } }, { $sort: { _id: 1 } }, { $project: { _id: 1, names: "$customer.name" } }]).toArray();
printjson(result);

The two orders receive customer-name arrays ["Mira"] and []. Keep the empty match visible if it matters to data quality. An appropriate foreign-field index can matter for performance, and a one-to-many match followed by unwinding can multiply rows in later calculations.

36. How should BSON dates and time zones be handled?

A BSON Date stores an instant as milliseconds relative to the Unix epoch, commonly expressed in UTC. It does not retain the original human time-zone label. Use explicit offsets when constructing instants and retain a separate zone when the application needs local calendar rules.

mongosh JavaScript

const c = db.getCollection("batch20261102_beginner_q36");
c.deleteMany({});
c.insertMany([{ _id: 1, occurredAt: ISODate("2026-11-02T12:00:00Z") }, { _id: 2, occurredAt: ISODate("2026-11-03T00:00:00Z") }]);
const result = c.find({ occurredAt: { $gte: ISODate("2026-11-02T00:00:00Z"), $lt: ISODate("2026-11-03T00:00:00Z") } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q36");
c.deleteMany({});
c.insertMany([{ _id: 1, occurredAt: ISODate("2026-11-02T12:00:00Z") }, { _id: 2, occurredAt: ISODate("2026-11-03T00:00:00Z") }]);
const result = c.find({ occurredAt: { $gte: ISODate("2026-11-02T00:00:00Z"), $lt: ISODate("2026-11-03T00:00:00Z") } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);
const c = db.getCollection("batch20261102_beginner_q36");
c.deleteMany({});
c.insertMany([{ _id: 1, occurredAt: ISODate("2026-11-02T12:00:00Z") }, { _id: 2, occurredAt: ISODate("2026-11-03T00:00:00Z") }]);
const result = c.find({ occurredAt: { $gte: ISODate("2026-11-02T00:00:00Z"), $lt: ISODate("2026-11-03T00:00:00Z") } }).sort({ _id: 1 }).toArray().map(d => d._id);
printjson(result);

Only ID 1 falls within the half-open UTC interval. The upper boundary excludes midnight of the next day. If the business asks for a local date, first derive the appropriate UTC boundaries for that zone, including daylight-saving changes, rather than assuming every local day is a fixed UTC window.

37. How does mongosh differ from an application driver?

mongosh is an interactive scripting shell with helpers for working with MongoDB. A driver integrates database operations into an application language and has its own connection, asynchronous execution, result and type-handling APIs. Shell code is not automatically a drop-in application snippet.

For example, a shell helper such as ISODate needs an appropriate date representation in the chosen driver. Application code also needs deliberate connection lifecycle and error handling. Preserve the query’s meaning while translating to the client API, and check the driver version rather than assuming every result wrapper matches mongosh.

38. What roles do primary and secondary members play in a replica set?

A replica set maintains copies of data across members. The primary handles writes, and secondaries replicate the primary’s operations; elections can select a new primary when needed. Reading from secondaries depends on the configured read preference and consistency requirements.

Replication supports availability but does not imply every secondary always has the newest write at the instant it is queried. A client must handle failover and the application’s read/write guarantees deliberately. Replica copies also replicate unwanted changes, so a replica set is not a replacement for a tested backup and recovery strategy.

39. How does sharding differ from replication?

Sharding distributes data across shards to scale storage or workload beyond one server’s resources. Replication maintains redundant copies for availability. A sharded deployment commonly uses replica sets as shards, so the two mechanisms can work together rather than being alternatives.

If a collection’s data must be distributed, the shard key influences placement and query targeting. Adding replicas does not automatically divide that collection’s primary write workload in the same way. Neither mechanism is a universal performance fix: assess the workload and data model before assuming more machines will solve an inefficient access pattern.

40. How does MongoDB Atlas differ from a self-managed deployment?

Atlas is MongoDB’s managed cloud service, while a self-managed deployment leaves infrastructure and database operations with the operating team. The core document model remains relevant in both, but deployment features, available configurations and operational responsibilities differ.

Atlas can handle parts of provisioning and operations, yet the application team still needs suitable data modeling, permissions, query design and recovery requirements. Self-management offers direct operational control while requiring the team to maintain and verify the deployment. Compare the actual service configuration and responsibilities rather than equating “managed” with no administration or “self-managed” with unrestricted compatibility.

MongoDB Interview Questions and Answers for Intermediate

The intermediate answers connect implementation details to correctness and cost. They explain expected results, configuration dependencies and failure cases rather than treating an operator as a complete solution.

41. How do access patterns guide a MongoDB document design?

Start with the operations the application must perform, including their frequency, returned fields and consistency requirements. Grouping data that is read and changed together can reduce round trips, but embedding everything creates different problems when related data grows or changes independently.

For an order details page, a snapshot of the purchased item name and price belongs naturally with the order because it records the transaction as it happened. A customer’s current contact details may remain in a separate customer document. Copying those details into every order requires a deliberate decision about whether each copy represents history or current truth.

Compare representative reads and writes before committing to the model. Include update fan-out, document growth and index requirements, not just a convenient sample response. The right boundary depends on the workload; MongoDB does not require every relationship to be embedded.

42. How would you prevent an embedded array from growing into an oversized document?

Give the array a justified upper bound or move its unbounded history into separate documents. MongoDB 8.0 limits a BSON document to 16 MiB, and approaching that limit can cause operational problems well before an insert or update is rejected.

A device document might keep its latest status and a small bounded set of recent alerts while a separate events collection stores the complete history. Another option is a bucket model with controlled time or size boundaries. A bucket still needs a rollover rule; calling an unbounded array a bucket does not solve its growth.

Estimate BSON size with realistic strings and nested fields, and observe the upper tail rather than average document size alone. Plan migration before the limit is reached. GridFS addresses large file storage, but it is not automatically the appropriate model for queryable event records.

43. How can JSON Schema validation enforce a useful document contract?

Use a collection validator to require critical fields and BSON types while allowing the evolution the application actually needs. A validator is a server-side write guard; it does not replace authorization, application-level feedback or relationships that span documents.

mongosh JavaScript: Run this fixture in a disposable practice database.

db.createCollection("iq_mongo_q43", {
  validator: { $jsonSchema: {
    bsonType: "object",
    required: ["sku", "quantity"],
    properties: {
      sku: { bsonType: "string" },
      quantity: { bsonType: "int", minimum: 0 }
    }
  } }
});
db.iq_mongo_q43.insertOne({sku: "A", quantity: NumberInt(2)});
db.createCollection("iq_mongo_q43", {
  validator: { $jsonSchema: {
    bsonType: "object",
    required: ["sku", "quantity"],
    properties: {
      sku: { bsonType: "string" },
      quantity: { bsonType: "int", minimum: 0 }
    }
  } }
});
db.iq_mongo_q43.insertOne({sku: "A", quantity: NumberInt(2)});
db.createCollection("iq_mongo_q43", {
  validator: { $jsonSchema: {
    bsonType: "object",
    required: ["sku", "quantity"],
    properties: {
      sku: { bsonType: "string" },
      quantity: { bsonType: "int", minimum: 0 }
    }
  } }
});
db.iq_mongo_q43.insertOne({sku: "A", quantity: NumberInt(2)});

The insert satisfies the contract. A negative quantity or a string quantity should fail validation under the default error action. The explicit NumberInt makes the intended BSON type visible rather than relying on a client’s number encoding.

Existing documents are not automatically repaired when a validator is introduced. Decide how to inspect and migrate them, and choose validation level and action deliberately. Overly restrictive rules can block a staged deployment in which old and new application versions temporarily coexist.

44. How would you evolve a field without breaking older documents and applications?

Use a staged compatibility plan: make readers tolerate the transition, introduce the new representation, backfill deliberately and remove the old representation only after its consumers are retired. A schema version field can identify meaning, but the version must correspond to implemented read and write behavior.

Suppose a single address string becomes structured address fields. A new reader can initially accept both forms while a controlled migration populates the new fields. Avoid silently deriving postal codes or regions from strings that cannot be parsed reliably; flag those records for a defined resolution path.

Track migration coverage and failed records. If both representations remain writable, define which is authoritative and how conflicts are prevented. Testing only newly inserted documents misses the main risk: real collections contain older, incomplete and occasionally malformed variants.

45. How does a version predicate prevent a lost update?

Include the version that was read in the update filter and increment it in the same single-document update. The write succeeds only if no other writer has changed that version, allowing the application to detect a stale edit instead of overwriting it.

mongosh JavaScript: Run this fixture in a disposable practice database.

db.iq_mongo_q45.insertOne({_id: 1, title: "Draft", version: 1});
const first45 = db.iq_mongo_q45.updateOne(
  {_id: 1, version: 1},
  {$set: {title: "Reviewed"}, $inc: {version: 1}}
);
const stale45 = db.iq_mongo_q45.updateOne(
  {_id: 1, version: 1},
  {$set: {title: "Stale edit"}, $inc: {version: 1}}
);
assert.eq(1, first45.matchedCount);
assert.eq(0, stale45.matchedCount);
db.iq_mongo_q45.insertOne({_id: 1, title: "Draft", version: 1});
const first45 = db.iq_mongo_q45.updateOne(
  {_id: 1, version: 1},
  {$set: {title: "Reviewed"}, $inc: {version: 1}}
);
const stale45 = db.iq_mongo_q45.updateOne(
  {_id: 1, version: 1},
  {$set: {title: "Stale edit"}, $inc: {version: 1}}
);
assert.eq(1, first45.matchedCount);
assert.eq(0, stale45.matchedCount);
db.iq_mongo_q45.insertOne({_id: 1, title: "Draft", version: 1});
const first45 = db.iq_mongo_q45.updateOne(
  {_id: 1, version: 1},
  {$set: {title: "Reviewed"}, $inc: {version: 1}}
);
const stale45 = db.iq_mongo_q45.updateOne(
  {_id: 1, version: 1},
  {$set: {title: "Stale edit"}, $inc: {version: 1}}
);
assert.eq(1, first45.matchedCount);
assert.eq(0, stale45.matchedCount);

The stored title remains Reviewed with version two. A zero match must be handled as a conflict or missing record, rather than reported as a successful save. Refetching and blindly retrying the old values would recreate the lost-update problem.

This protects the selected document and cooperating writers. Every write path that changes the protected state must respect the version protocol; it does not establish an invariant across unrelated documents.

46. How do arrayFilters update selected elements inside a document?

Use a filtered positional identifier to select all array elements that satisfy an explicit condition. The outer filter selects documents; arrayFilters selects elements within those documents. These are separate decisions.

mongosh JavaScript: Run this fixture in a disposable practice database.

db.iq_mongo_q46.insertOne({_id: 1, lines: [
  {sku: "A", qty: 2}, {sku: "B", qty: 0}, {sku: "C", qty: 0}
]});
db.iq_mongo_q46.updateOne(
  {_id: 1},
  {$set: {"lines.$[line].status": "empty"}},
  {arrayFilters: [{"line.qty": 0}]}
);
assert.eq(["B", "C"], db.iq_mongo_q46.findOne({_id: 1}).lines
  .filter(x => x.status === "empty").map(x => x.sku));
db.iq_mongo_q46.insertOne({_id: 1, lines: [
  {sku: "A", qty: 2}, {sku: "B", qty: 0}, {sku: "C", qty: 0}
]});
db.iq_mongo_q46.updateOne(
  {_id: 1},
  {$set: {"lines.$[line].status": "empty"}},
  {arrayFilters: [{"line.qty": 0}]}
);
assert.eq(["B", "C"], db.iq_mongo_q46.findOne({_id: 1}).lines
  .filter(x => x.status === "empty").map(x => x.sku));
db.iq_mongo_q46.insertOne({_id: 1, lines: [
  {sku: "A", qty: 2}, {sku: "B", qty: 0}, {sku: "C", qty: 0}
]});
db.iq_mongo_q46.updateOne(
  {_id: 1},
  {$set: {"lines.$[line].status": "empty"}},
  {arrayFilters: [{"line.qty": 0}]}
);
assert.eq(["B", "C"], db.iq_mongo_q46.findOne({_id: 1}).lines
  .filter(x => x.status === "empty").map(x => x.sku));

Both zero-quantity lines receive the status; the first line does not. The identifier must follow MongoDB’s naming rules, and supported filter expressions have restrictions. Do not assume that every aggregation expression can be placed inside arrayFilters.

For upserts, filtered positional updates have additional array-equality requirements when an insertion occurs. When the array is absent or its shape differs, choose an explicit initialization path rather than expecting the positional update to invent a suitable structure.

47. When can the positional dollar operator update the wrong array element?

The positional $ operator uses an array match from the query to update an element, but it is unsuitable when the query’s matching context is ambiguous. Filtering on several arrays can make it unclear which position the update should use.

For example, a document containing both enrolled courses and active terms should not rely on a query matching each array independently to identify one course-term relationship. If those values belong together, represent that relationship explicitly and use $elemMatch for same-element conditions, with filtered positional identifiers where the update needs precise element selection.

Also distinguish updating the first matched element from updating every qualifying element. A test with one array member can conceal this difference. Include duplicate matches and nested-array cases in fixtures, then select the appropriate positional operator instead of treating $ as a generic array traversal mechanism.

48. When is an aggregation pipeline useful inside an update?

A pipeline update is useful when the new value depends on existing fields or requires an expression-based transformation. Supported update-pipeline stages are a restricted subset of aggregation stages; it is not a full reporting pipeline attached to a write.

mongosh JavaScript: Run this fixture in a disposable practice database.

db.iq_mongo_q48.insertOne({_id: 1, subtotal: 80, shipping: 5});
db.iq_mongo_q48.updateOne({_id: 1}, [
  {$set: {total: {$add: ["$subtotal", "$shipping"]}}},
  {$set: {label: {$literal: "$priority"}}}
]);
assert.eq(85, db.iq_mongo_q48.findOne({_id: 1}).total);
assert.eq("$priority", db.iq_mongo_q48.findOne({_id: 1}).label);
db.iq_mongo_q48.insertOne({_id: 1, subtotal: 80, shipping: 5});
db.iq_mongo_q48.updateOne({_id: 1}, [
  {$set: {total: {$add: ["$subtotal", "$shipping"]}}},
  {$set: {label: {$literal: "$priority"}}}
]);
assert.eq(85, db.iq_mongo_q48.findOne({_id: 1}).total);
assert.eq("$priority", db.iq_mongo_q48.findOne({_id: 1}).label);
db.iq_mongo_q48.insertOne({_id: 1, subtotal: 80, shipping: 5});
db.iq_mongo_q48.updateOne({_id: 1}, [
  {$set: {total: {$add: ["$subtotal", "$shipping"]}}},
  {$set: {label: {$literal: "$priority"}}}
]);
assert.eq(85, db.iq_mongo_q48.findOne({_id: 1}).total);
assert.eq("$priority", db.iq_mongo_q48.findOne({_id: 1}).label);

The first stage computes the total from the current document. The second uses $literal because a string beginning with a dollar sign would otherwise be interpreted as an expression reference. This distinction matters when application values are inserted into pipeline expressions.

Validate numeric types and missing-field behavior before applying the transformation broadly. The update remains atomic per document, but updating many documents does not make the entire multi-document operation an all-or-nothing transaction.

49. How do ordered and unordered bulk writes behave when one operation fails?

An ordered bulk processes operations in order and stops after an error; successful earlier operations remain applied unless a surrounding transaction changes that outcome. An unordered bulk attempts remaining operations despite individual errors and must not be used when correctness depends on execution order.

Consider three inserts where the second violates a unique key. In an ordered bulk, the first can persist and the third is not attempted. In an unordered bulk, the third may succeed. The application should inspect the bulk error details and write counts instead of assuming that one exception means nothing was written.

Assign stable identities to retryable business records and reconcile partial success before resubmitting. A bulk write is a batching facility, not an automatic transaction or a universal retry strategy. The collection-level bulkWrite method and MongoDB 8.0’s cross-namespace bulk facilities also have different interfaces, so state which API an example uses.

50. How would you implement stable range pagination for a sorted result?

Use the last returned sort keys as a continuation boundary and include a unique tie-breaker. This avoids progressively skipping large prefixes, but it requires an index and predicate that match the chosen ordering.

mongosh JavaScript: Run this fixture in a disposable practice database.

db.iq_mongo_q50.insertMany([
  {_id: 1, score: 10}, {_id: 2, score: 10}, {_id: 3, score: 20}
]);
db.iq_mongo_q50.createIndex({score: 1, _id: 1});
const next50 = db.iq_mongo_q50.find({$or: [
  {score: {$gt: 10}}, {score: 10, _id: {$gt: 1}}
]}).sort({score: 1, _id: 1}).limit(2).toArray();
assert.eq([2, 3], next50.map(x => x._id));
db.iq_mongo_q50.insertMany([
  {_id: 1, score: 10}, {_id: 2, score: 10}, {_id: 3, score: 20}
]);
db.iq_mongo_q50.createIndex({score: 1, _id: 1});
const next50 = db.iq_mongo_q50.find({$or: [
  {score: {$gt: 10}}, {score: 10, _id: {$gt: 1}}
]}).sort({score: 1, _id: 1}).limit(2).toArray();
assert.eq([2, 3], next50.map(x => x._id));
db.iq_mongo_q50.insertMany([
  {_id: 1, score: 10}, {_id: 2, score: 10}, {_id: 3, score: 20}
]);
db.iq_mongo_q50.createIndex({score: 1, _id: 1});
const next50 = db.iq_mongo_q50.find({$or: [
  {score: {$gt: 10}}, {score: 10, _id: {$gt: 1}}
]}).sort({score: 1, _id: 1}).limit(2).toArray();
assert.eq([2, 3], next50.map(x => x._id));

The boundary follows the first row with score ten, so the next page includes the other tied row before score twenty. A predicate on score alone would incorrectly skip that tie.

Range pagination does not freeze changing data. Updates to sort keys or new inserts can change page membership between requests. Define whether the product needs a live view, an immutable ordering key or a consistent snapshot, and encode all required filters in the continuation contract.

51. Why can an anchored regular expression use an index more effectively?

A case-sensitive prefix expression can let MongoDB restrict an index scan to values beginning with that prefix. An unanchored substring search generally offers a less selective starting range, so having an index on the field does not guarantee an efficient search.

For example, a search beginning with ^ABC against a suitable string index can narrow candidate keys for codes that start with ABC. The actual expression matters: extra wildcards and case-insensitive options can change the work required. A case-insensitive collation index does not make the $regex operator collation-aware.

Inspect the execution plan and examined-key counts for representative patterns. Escape user input when the requirement is a literal prefix rather than a user-supplied regex language. For richer search requirements, evaluate an appropriate search facility rather than stretching a basic B-tree index into a full text-search engine.

52. Why might a query with collation fail to use the expected string index?

The query’s collation must be compatible with the index’s collation for the relevant string comparisons. An index built with one set of language and comparison rules cannot generally answer a different string ordering as though the rules were identical.

If an index uses an English case-insensitive collation but a query uses simple binary comparison, the application has requested different semantics. Specify the intended collation consistently when building the index and issuing the query, and verify the plan. A compound index may still support a compatible non-string prefix even when later string comparison cannot use it fully.

Collation changes equality and sorting, which can affect uniqueness and user-visible order. Test accented characters, case variants and the actual supported languages. Treat collation as part of the data contract, not merely a switch to make one slow query use an index.

53. When can a query use a partial index?

A partial index contains only documents that meet its filter. To use it without losing results, the query must imply that filter or a sufficiently restrictive subset; a query that needs excluded documents cannot rely on the partial index as its complete access path.

For a queue with many completed jobs, an index restricted to status: "open" can efficiently support open-job lookups. A query for every job owned by a user does not have the same eligibility, because completed jobs are absent from the index.

Choose the partial condition from a stable workload and inspect representative plans. Partial indexes save storage and maintenance only for excluded entries; they also add a contract that queries must satisfy. If the application omits the status predicate after a refactor, performance can change even though the index still exists.

54. How do sparse and partial unique indexes handle optional identifiers differently?

A sparse index omits documents missing its indexed field, while a partial index lets you define a more explicit inclusion condition. Uniqueness is enforced among the indexed entries, so the inclusion rule determines which optional values participate.

For an optional email field, missing and explicit null are different cases. A single-field sparse unique index can omit missing fields but still index an explicit null. A partial unique index restricted to string values can enforce uniqueness only for actual strings, if that matches the application’s definition of a usable email.

Normalize and validate values separately: an empty string is still a string, and case-equivalent addresses need a deliberate comparison policy. Do not assume that sparse means ignore every empty-looking value. Test missing, null, empty, valid and duplicate values before adopting the uniqueness rule.

55. Why should an application still check expiry when it uses a TTL index?

TTL deletion is asynchronous background cleanup, not an exact deadline at which a document becomes inaccessible. An expired record can remain queryable until the deletion process handles it, especially under load.

For a session with an expiresAt BSON date, a single-field TTL index with expireAfterSeconds: 0 can remove the record after that date. Authentication should still reject it when the current time reaches the expiry boundary rather than accepting it because a lookup found the document.

Validate that the indexed field uses the expected date type and plan for the deletion load when adding TTL to an existing collection. Cleanup timing, application validity and mandatory retention requirements are separate concerns. TTL is inappropriate when records must be retained until a separate business condition has been verified.

56. What makes a query covered by an index?

A covered query can satisfy its filter and returned fields from index keys without fetching the full documents. This requires the relevant fields to be in an eligible index and the projection to avoid extra document fields.

For an index on {customerId: 1, status: 1}, a query filtering by customer and projecting only those fields can potentially be covered when it explicitly excludes _id. Leaving the default _id projection in place can require a document fetch because that field is not automatically part of this secondary index.

Verify with the execution plan and document-examination counters rather than inferring coverage from the index definition alone. Multikey fields, null predicates and sharded-query requirements introduce additional restrictions. Coverage can reduce reads, but adding many projected fields to every index increases storage and write maintenance.

57. How do you choose between equality-sort-range and equality-range-sort index ordering?

Place equality fields where they narrow the relevant index prefix, then decide whether avoiding a blocking sort or reducing the range scan matters more. Equality-sort-range is a useful guideline, not a rule that makes selectivity and result limits irrelevant.

For a customer’s recent orders sorted by amount, putting the sort key before a date range can support ordered scanning but may examine many dates. Putting a highly selective date range first can reduce candidates while requiring a separate sort. A small result limit can also change which plan does less work.

Compare both candidates using realistic distributions, sort direction and result limits. Record keys examined, documents examined and sorting behavior, alongside latency. A tiny uniform fixture cannot establish the better production index when actual customers have very different order counts.

58. What should you inspect in explain executionStats beyond the winning plan name?

Inspect how much work produced the result: returned documents, examined keys, examined documents and relevant sort or fetch stages. A plan containing an index scan can still perform poorly if it scans a large portion of the index before returning a few rows.

For a query returning ten rows after examining a million keys, investigate selectivity, compound-key ordering and residual filters. A large difference between keys and documents examined can mean filtering occurs at different stages; interpret it in the context of the plan rather than expecting a universal ideal ratio.

executionStats executes the query to collect statistics, so use an appropriately bounded diagnostic workload. Explain output shape can differ by execution engine and server version. Combine it with repeated workload measurements and operational telemetry; one explain duration is not a reliable latency benchmark.

59. How should you handle an aggregation sort that needs substantial memory?

First check whether the pipeline can use an index for the required order or reduce the rows and fields reaching the sort without changing the result. Allowing disk use can make a supported stage complete, but does not make a large sort inexpensive.

MongoDB 8.0 inherits the server-level allowDiskUseByDefault behavior introduced in 6.0 for eligible aggregation stages exceeding their memory threshold; a command-level option can override the relevant default. Disk spilling adds I/O and may still fail if storage is exhausted or the stage has a separate limit.

For a top-results query, a correctly placed sort and limit can reduce work, while moving the limit before the sort changes which records are considered. Inspect the plan, spill evidence and disk budget. Do not assume that every aggregation stage can spill simply because allowDiskUse is enabled.

60. How can pipeline stage order change both performance and meaning?

Move selective filters early when they depend only on fields available at that point, but preserve the semantics of computed fields, array expansion and grouping. MongoDB can perform some optimizations automatically; it cannot safely apply arbitrary reorderings.

Filtering orders by tenant before unwinding their line items reduces input without changing which tenant is included. Filtering a computed order total must occur after the total exists, unless the condition is correctly rewritten. A filter before $unwind can select documents containing a matching element while still allowing other elements to emerge; filtering after unwinding selects individual emitted elements.

Use small fixtures that distinguish these cases, then inspect the optimized plan for the real workload. Early projection is not always a necessary optimization because the engine can already track required fields. Prefer transformations that demonstrably reduce expensive work without altering the question the pipeline answers.

61. How do you keep a facet aggregation from building an oversized result?

Bound each facet’s output and reduce its input where possible. A facet can compute several summaries over the same incoming documents, but collecting every matching record into one output array can exceed its limits.

For a product search, one branch might count brands while another returns only the requested page. Keep the page bounded and consider how many distinct brands or categories the other branches can emit. MongoDB 8.0 applies a 100 MB limit to the resulting document during facet processing, and the final BSON output document must fit within 16 MiB. The facet stage cannot spill to disk to escape its own limit.

A preceding eligible match can use an index; placing the facet first does not create an index lookup inside each branch. If one branch needs an unbounded export, separate that workflow rather than forcing it into a compact search-response document.

62. What determines whether a correlated lookup can use a foreign index?

The foreign predicate and index must support the comparison being made. In a lookup pipeline, certain comparisons inside $expr can use an index when they compare a foreign field with a value that resolves as a constant for the lookup invocation; comparisons between two foreign fields do not have the same opportunity.

For example, an order’s customer ID can be passed through let and compared with an indexed customer identifier. Missing or empty bound values and multikey-index restrictions can prevent the expected index use. The fact that an index exists does not establish that a correlated expression is eligible to use it.

Keep the outer input selective and return only necessary foreign results. Inspect the actual plan and matching cardinality, especially when one order can join many records. An efficient foreign lookup repeated for millions of outer documents can still be expensive.

63. How can setWindowFields calculate a running total without collapsing rows?

Partition the documents by the relevant entity, define their order and specify a window ending at the current document. Unlike grouping, the window stage adds a calculation to each document instead of reducing the partition to one result.

mongosh JavaScript: Run this fixture in a disposable practice database.

db.iq_mongo_q63.insertMany([
  {_id: 1, account: "A", amount: 4},
  {_id: 2, account: "A", amount: 6},
  {_id: 3, account: "B", amount: 9}
]);
const rows63 = db.iq_mongo_q63.aggregate([
  {$setWindowFields: {
    partitionBy: "$account", sortBy: {_id: 1},
    output: {running: {$sum: "$amount",
      window: {documents: ["unbounded", "current"]}}}
  }},
  {$sort: {_id: 1}}
]).toArray();
assert.eq([4, 10, 9], rows63.map(x => x.running));
db.iq_mongo_q63.insertMany([
  {_id: 1, account: "A", amount: 4},
  {_id: 2, account: "A", amount: 6},
  {_id: 3, account: "B", amount: 9}
]);
const rows63 = db.iq_mongo_q63.aggregate([
  {$setWindowFields: {
    partitionBy: "$account", sortBy: {_id: 1},
    output: {running: {$sum: "$amount",
      window: {documents: ["unbounded", "current"]}}}
  }},
  {$sort: {_id: 1}}
]).toArray();
assert.eq([4, 10, 9], rows63.map(x => x.running));
db.iq_mongo_q63.insertMany([
  {_id: 1, account: "A", amount: 4},
  {_id: 2, account: "A", amount: 6},
  {_id: 3, account: "B", amount: 9}
]);
const rows63 = db.iq_mongo_q63.aggregate([
  {$setWindowFields: {
    partitionBy: "$account", sortBy: {_id: 1},
    output: {running: {$sum: "$amount",
      window: {documents: ["unbounded", "current"]}}}
  }},
  {$sort: {_id: 1}}
]).toArray();
assert.eq([4, 10, 9], rows63.map(x => x.running));

Account A accumulates four and then ten; account B starts a separate total at nine. The explicit final sort establishes presentation order, because the window stage is not a guarantee of final returned order.

Choose document or value-range windows deliberately. Three previous records are not necessarily three previous days, and tied sort values need a defined interpretation. Check the supported sort and window restrictions for the chosen operator.

64. Why does dateTrunc need an explicit timezone for business-day reporting?

A BSON date identifies an instant, while a business day depends on a timezone. Truncating without the intended timezone can place events near midnight into a different day from the one users expect.

mongosh JavaScript: Run this fixture in a disposable practice database.

db.iq_mongo_q64.insertOne({_id: 1,
  at: ISODate("2026-01-01T00:30:00Z")});
const row64 = db.iq_mongo_q64.aggregate([
  {$project: {day: {$dateTrunc: {
    date: "$at", unit: "day", timezone: "America/New_York"
  }}}}
]).toArray()[0];
assert.eq("2025-12-31T05:00:00.000Z", row64.day.toISOString());
db.iq_mongo_q64.insertOne({_id: 1,
  at: ISODate("2026-01-01T00:30:00Z")});
const row64 = db.iq_mongo_q64.aggregate([
  {$project: {day: {$dateTrunc: {
    date: "$at", unit: "day", timezone: "America/New_York"
  }}}}
]).toArray()[0];
assert.eq("2025-12-31T05:00:00.000Z", row64.day.toISOString());
db.iq_mongo_q64.insertOne({_id: 1,
  at: ISODate("2026-01-01T00:30:00Z")});
const row64 = db.iq_mongo_q64.aggregate([
  {$project: {day: {$dateTrunc: {
    date: "$at", unit: "day", timezone: "America/New_York"
  }}}}
]).toArray()[0];
assert.eq("2025-12-31T05:00:00.000Z", row64.day.toISOString());

The event falls on December 31 in New York, and that day’s midnight is represented as 05:00 UTC. The output is still a date instant, not a timezone-bearing formatted string.

Use an Olson timezone identifier when daylight-saving rules matter, rather than a fixed offset that works only part of the year. Keep grouping boundaries and display labels consistent, and test dates around clock changes when reporting calendar periods.

65. How should you preserve decimal meaning in monetary calculations?

Use an intentional numeric representation, such as Decimal128 with decimal inputs or integer minor units with a documented scale. Binary floating-point values do not exactly represent every decimal fraction, and converting an already rounded value later does not recover the original intent.

mongosh JavaScript: Run this fixture in a disposable practice database.

db.iq_mongo_q65.insertOne({_id: 1,
  price: NumberDecimal("0.10"), quantity: NumberInt(3)});
const row65 = db.iq_mongo_q65.aggregate([
  {$project: {total: {$multiply: ["$price", "$quantity"]}}}
]).toArray()[0];
assert.eq("0.30", row65.total.toString());
db.iq_mongo_q65.insertOne({_id: 1,
  price: NumberDecimal("0.10"), quantity: NumberInt(3)});
const row65 = db.iq_mongo_q65.aggregate([
  {$project: {total: {$multiply: ["$price", "$quantity"]}}}
]).toArray()[0];
assert.eq("0.30", row65.total.toString());
db.iq_mongo_q65.insertOne({_id: 1,
  price: NumberDecimal("0.10"), quantity: NumberInt(3)});
const row65 = db.iq_mongo_q65.aggregate([
  {$project: {total: {$multiply: ["$price", "$quantity"]}}}
]).toArray()[0];
assert.eq("0.30", row65.total.toString());

Constructing the price from a string preserves the intended decimal input. Define rounding at the business boundary, including currency scale and whether rounding occurs per line or after summation. These choices can change an invoice even when every stored value uses Decimal128.

Enforce compatible types during ingestion and decide how clients serialize decimal results. Turning every result into a JavaScript number can reintroduce floating-point limitations outside the database. Decimal128 improves representation; it does not decide the accounting policy.

66. Does unionWith remove duplicate records from combined collections?

No. $unionWith combines result streams and can include duplicates. If the task requires one record per business entity, add a deliberate reconciliation step rather than expecting SQL-style distinct union semantics.

Suppose current leads contain IDs A and B while an imported collection contains B and C. Combining the streams produces four records, including two representations of B. Grouping by the lead ID can produce three entities, but the application must define which fields win when the two B records disagree.

Do not rely on unspecified stream order to choose a preferred version. Add provenance, timestamps and a deterministic selection rule when reconciling sources, then sort the final result if order matters. Two documents with different database IDs can still be the same business entity, so deduplicating on _id alone may be wrong.

67. What must you decide before materializing aggregation output with merge?

Define the output identity, match behavior and refresh semantics. $merge writes aggregation results to a collection; it does not automatically maintain a live view or remove old output rows that disappear from the source result.

For a daily sales summary, use a stable key for the day and business dimension and choose whether a matching row is replaced, merged or updated through an allowed pipeline. MongoDB requires a suitable unique index for the chosen on fields. Under the 8.0 baseline, those fields cannot be missing or null in input documents.

A rerun must not accidentally add the same total twice. Plan how to handle a day that now has no qualifying sales, because its old materialized row can remain unless explicitly reconciled. A failure can leave earlier output writes applied, so refresh design must account for partial completion.

68. Why must every operation in a transaction use the same session?

The session identifies the transaction context. Operations issued through a different session or an ordinary collection handle can execute outside that transaction, even when the application code places them beside transactional statements.

For a transfer, both account updates and any transactional ledger insertion must use handles associated with the transaction’s session. In a driver, this often means passing the session to each operation; in mongosh, use the database and collection obtained through the session. Do not assume lexical nesting alone enrolls an operation.

Transactions require an appropriate replica set or sharded deployment, not a standalone server. Keep the transaction short and avoid unrelated remote calls while it is open. An email or external payment request is not rolled back by aborting MongoDB writes, so coordinate such effects through an application design that tolerates retries.

69. How do local, majority and snapshot read concerns differ in application behavior?

local can return data that has not become majority committed and may later be rolled back. majority reads majority-committed data. snapshot provides a view from a single point in time for supported operations and contexts, which is a different requirement from simply avoiding uncommitted replication history.

A report reading several related records may require a consistent snapshot rather than independently reading the most recent available value for each step. Conversely, a low-latency status display may deliberately tolerate weaker guarantees. Read preference still determines eligible servers; read concern does not by itself mean read the latest primary state.

For snapshot transactions, the documented majority-committed snapshot guarantees depend on committing with majority write concern. Specify the scope and durability requirements together. Avoid describing majority as linearizable or assuming that several independent majority reads necessarily share one snapshot.

70. How do write concern and journaling answer different durability questions?

Write concern specifies the acknowledgement required from the deployment, while journaling concerns persistence to an on-disk recovery log. Replication acknowledgement and local persistence are related but distinct; neither should be inferred from the other without checking configuration.

For a replica-set write, w: "majority" requests the relevant majority acknowledgement. With the usual writeConcernMajorityJournalDefault: true configuration, majority acknowledgement incorporates journaling behavior on the acknowledging members. Explicit j: true requests journal acknowledgement where supported, but a journaled write acknowledged only by one primary can still be rolled back after failover.

A write-concern timeout does not undo a write that already happened. Treat that result as an acknowledgement failure with a potentially applied operation, then use the application’s identity and reconciliation rules. Choose the concern from recovery requirements and deployment topology rather than relying on an unexplained connection-string default.

71. Why can a secondary read return an older value after a successful write?

Replication is asynchronous, so a secondary selected by read preference may not yet have applied the write. Routing reads away from the primary is a placement decision, not an automatic read-your-writes guarantee.

A profile update followed by a secondary read might briefly show the old display name. Options include using an appropriate causally consistent session with the required concerns or selecting a different read policy for that workflow. The choice depends on whether stale results are acceptable and what latency or availability cost the application can tolerate.

maxStalenessSeconds filters secondary candidates using an estimate of staleness; it is not a per-record freshness certificate. nearest means a latency-based eligible-server selection, not the server with the newest data. Test failover and lag behavior, not only healthy single-client reads.

72. What conditions provide the full causal guarantees of a session?

Use a causally consistent session with majority read concern and majority write concern for the documented full set of causal guarantees with durability. This supports relationships such as reading one’s own writes and observing reads and writes in causal order.

For example, a user creates a record and then retrieves it through another eligible member using the same causal session. The read can wait for the causal point instead of returning an older state. That is different from running two unrelated operations that happen to use the same database connection pool.

Do not run concurrent operations in a session as though it were a general shared synchronization object. Causal consistency does not make all clients’ actions globally serializable or eliminate application conflicts. If causal context moves between sessions, follow the driver’s supported propagation rules rather than copying arbitrary timestamps into queries.

73. What do retryable writes protect against, and what do they not cover?

Eligible retryable writes let a compatible driver retry a supported operation after certain network or primary-selection failures without treating the retry as a new independent write. They require an appropriate replica set or sharded deployment and acknowledged writes.

This does not make every operation retryable. Multi-document updates are not covered like eligible single-document writes, and writes inside a transaction are not individually retried through this mechanism. Transaction commit and transaction-body recovery have their own rules.

A new application request is also not automatically recognized as the same business action. If a user resubmits an order after losing an HTTP response, use a business idempotency key or other reconciliation contract. Retryable writes address supported database-operation retries; they do not make external effects or a multi-step business workflow exactly once.

74. How should transaction recovery distinguish a transient error from an uncertain commit?

A transient transaction error can require retrying the transaction body, while an unknown commit result requires resolving or retrying commit according to the supported transaction API. Treating both as simply rerun everything risks repeating business work after a transaction may already have committed.

Use the driver’s convenient transaction API where suitable and understand its retry contract. The callback can run more than once, so it must not send an irreversible external notification or generate a new business identity on every invocation without protection.

For a core API implementation, inspect documented error labels and preserve session and transaction context for commit handling. Apply bounded operational deadlines and surface unresolved outcomes for reconciliation. Not every transaction error is transient: invalid data, unsupported operations and some resource failures need a design or input correction rather than an endless retry loop.

75. How should a change-stream consumer persist its resume position?

Save the resume token in coordination with durable processing of the corresponding event. Saving it before the effect is safely applied can skip work after a crash; saving it afterward can cause an event to be processed again, so consumers commonly need idempotent handling.

For a search-index updater, use the source document identity and a suitable version or event-processing contract to tolerate replay. Keep the resume token in its complete BSON representation and do not modify the event’s token field in a pipeline. A token is not simply an application timestamp that can be reconstructed later.

Resumption requires sufficient retained history and compatible stream options. If the token is no longer usable, follow a deliberate rebuild or reconciliation path instead of silently starting at now. Change streams require a supported replica set or sharded topology; they do not provide unlimited replay history or automatic exactly-once side effects.

76. How do connection-pool waits differ from server-selection and operation timeouts?

A pool wait means an operation is waiting for an available connection; server selection means the driver is seeking a server that satisfies topology and read-preference requirements. An operation deadline limits another part or the overall duration of work, depending on the driver and option used.

A burst of requests can exhaust a small pool even when the database is healthy. Increasing the pool may reduce waiting but can also increase server concurrency and contention. Conversely, a failover can cause selection delays that adding connections does not solve.

Reuse the driver’s intended client lifecycle and observe pool checkout, selection and execution separately. Option names and interactions differ across drivers and versions, so use the relevant driver documentation rather than assuming a universal timeout setting. Set bounds that fit the request budget and handle timeout results according to whether the operation may have reached the server.

77. How would you limit a MongoDB application account to its actual work?

Grant privileges for the operations and resources the application needs, using built-in roles only when their scope is appropriate and custom roles when narrower access is justified. Separate routine application access from schema migration, backup and administrative work.

A service that reads a catalog and updates its own task collection does not need broad administrative control over every database. Map its real commands, including aggregation output or index-management operations, before selecting roles. Otherwise, a missing privilege may appear only in an uncommon path and tempt someone to grant an overly broad role.

Test both permitted and denied operations with the intended account in a controlled environment. Database roles do not automatically enforce every tenant-level business rule inside a shared collection; the application’s query and authorization design must still prevent cross-tenant access. Rotate credentials without embedding them in source code or diagnostic output.

78. Why are TLS, authentication and authorization separate MongoDB controls?

TLS protects the transport and supports endpoint identity validation; authentication establishes a principal; authorization determines what that principal may do. Enabling one does not automatically configure the others correctly.

A client can use an encrypted connection yet connect to an untrusted endpoint if certificate validation is disabled. An authenticated application can still have excessive privileges. Conversely, a valid server certificate does not establish that an unauthenticated client should be allowed to read a collection.

Use trusted certificate chains and hostname validation, an appropriate authentication mechanism and narrowly scoped roles together. Test expiry and credential rotation through the supported deployment process. Avoid fixing a certificate error by permanently allowing invalid certificates, because that removes the identity check the secure connection depends on.

79. What makes a MongoDB backup suitable for a consistent restore?

The backup method must capture a recoverable state across the relevant data and metadata while accounting for concurrent writes and deployment topology. Copying some collection files or exporting collections at unrelated times does not establish a coherent point-in-time backup.

For a replica set, a supported logical backup workflow may use oplog capture and replay within its documented restrictions. A sharded deployment needs coordinated treatment across shards and configuration metadata; a procedure that is valid for a single replica set should not be assumed sufficient for the whole cluster.

Validate the restore in an isolated environment using application invariants, indexes, users or external dependencies as appropriate to the backup scope. Record tool and server compatibility, encryption-key availability and recovery objectives. A successful backup command proves that the command completed, not that the business can recover within its required time and data-loss limits.

80. How can slow-query diagnostics expose sensitive information?

Profiling and diagnostic logs can contain query shapes, values and operational context that reveal personal data or secrets. Collect only the detail needed for diagnosis and restrict access, retention and export of that evidence.

Begin with aggregate performance signals and a narrowly scoped investigation. If detailed profiling is justified, choose a bounded duration and supported filtering or sampling options appropriate to the deployment, and inspect the resulting records for sensitive literals. Enabling broad profiling can also add overhead and alter the workload being investigated.

Correlate query identifiers, examined work and latency without pasting raw customer predicates into tickets or chat. Redaction facilities and profiler behavior vary by deployment and version; verify what is actually captured. Stop or revert temporary diagnostic settings through the approved operational workflow once the evidence is sufficient.

MongoDB Interview Questions and Answers for Experienced

Experienced answers examine sharding, failure recovery, security and workload-specific trade-offs. They distinguish documented guarantees from assumptions that require deployment-level verification.

81. How would you evaluate shard-key cardinality and value frequency together?

Cardinality measures how many distinct key values exist; frequency reveals whether a few values dominate the workload. A key with a million values can still be unsuitable if one customer owns most documents or generates most writes. Evaluate distribution, query targeting and growth together.

For example, a tenant identifier gives convenient tenant-scoped queries, but a tenant holding 60% of the data remains an indivisible key value if that identifier is the complete shard key. Adding a useful suffix may create smaller ranges, at the cost of changing which requests target a narrow range.

Use representative production distributions and expected future tenants, rather than a uniformly generated benchmark. Distinguish document-count imbalance from request-rate imbalance: evenly distributed bytes can conceal one very busy shard.

82. When does a monotonically increasing shard key create a hotspot?

A ranged shard key that increases with each insert concentrates new writes in the range containing the highest values. Moving older ranges can distribute stored data without spreading the current insertion workload.

A timestamp-only key illustrates the problem: yesterday’s data may occupy several shards while today’s inserts repeatedly hit one range. Hashing a suitable key can distribute inserts, but a time-range query generally loses the routing advantage of contiguous time ranges.

Compare the full workload before choosing hashing. A compound key may preserve an important routing prefix while distributing work within that scope. Hashing does not increase the number of distinct values or make an extremely frequent single value divisible.

83. How do you diagnose unexpected scatter-gather queries?

Inspect the actual query predicate, shard-key definition and explain output through mongos. A query can use an efficient index on each shard yet still contact many shards because its predicate does not constrain the relevant shard-key ranges.

For a collection partitioned by tenant and region, a request containing only a customer email might require broad routing even when email is indexed. Adding the authenticated tenant scope can improve both isolation and routing, provided the key design supports that targeting.

Do not infer routing from response time alone. Compare shards contacted, documents and keys examined, merge work and slowest-shard latency. A low-volume development cluster can hide the coordination cost that appears when shard count grows.

84. What do zones guarantee, and what locality problems remain?

Zones associate shard-key ranges with eligible shards so the balancer can place those ranges according to the configured policy. They express data placement intent; they do not make every request local or establish a complete jurisdictional compliance guarantee.

A regional tenant range may be assigned to shards in that region, while an application still connects through a distant router or joins with data elsewhere. Backups, logs, replica placement and administrative exports require separate examination.

Validate range boundaries, eligible capacity and placement convergence. A zone with too little capacity cannot be repaired by adding capacity only outside that zone. Include failover and maintenance behavior in the locality design, not just steady-state primary placement.

85. What makes a resharding plan operationally credible?

A resharding plan demonstrates that the new key improves observed workloads and that the cluster can sustain the migration’s additional resource demand. It also establishes compatibility, monitoring, interruption procedures and application expectations for the MongoDB 8.0 deployment.

Test representative routing and distribution before moving the real collection. Account for temporary storage, replication traffic and contention with normal writes. Existing unique indexes must satisfy the new shard-key requirements; a better-looking distribution does not override uniqueness constraints.

Define success in terms of targeted queries, balanced workload and acceptable latency after completion. Coordinate incompatible schema or index maintenance with the operation. Resharding changes distribution; it does not automatically fix expensive aggregations or poorly bounded application requests.

86. How does refining a shard key differ from resharding?

Refining adds suffix fields to the existing shard key. Resharding changes the shard-key definition more broadly and redistributes data for that definition. Refinement is useful when the existing prefix remains valuable but its values need more subdivision.

If the key is tenantId, refining it with orderId can make a large tenant’s data divisible. It does not remove tenantId as the leading field or immediately redistribute all existing chunks. Subsequent splitting and migration still matter.

Choose resharding when the original leading dimension is fundamentally wrong for the workload. Before refinement, confirm suffix availability, supporting indexes and query behavior. A suffix whose value is missing or identical on most documents may offer little practical improvement.

87. How do unique indexes constrain a sharded data model?

For a sharded collection, supported unique indexes generally require the shard key as a prefix so uniqueness can be enforced with the distribution model. A unique index that works on an unsharded collection is not automatically a valid globally enforced constraint after sharding.

For tenant-scoped order numbers, a compound unique index beginning with the shard key may express the intended rule. For a globally unique business identifier that is unrelated to that key, the architecture needs a compatible distribution or a separate authoritative allocation mechanism.

The default _id index also needs care: when _id is not the shard key, its uniqueness is enforced per shard rather than across the whole cluster. Generating globally unique identifiers remains an application responsibility in that design; do not assume the presence of the index proves global enforcement.

88. Why can migration and orphan documents complicate reads?

During range migration, physical copies can temporarily exist outside their current ownership. MongoDB uses ownership metadata and cleanup mechanisms to manage this, so inspecting a shard directly is not equivalent to querying the logical collection through mongos.

A direct shard count can include data that the shard no longer owns and therefore disagree with a routed application view. MongoDB 8.0 also documents special concerns for available read concern on sharded collections, including orphan visibility during migration.

Diagnose using the intended routing and read semantics. Correlate discrepancies with migration and cleanup state before declaring duplicates in the business dataset. Avoid manual deletion of internal-looking copies as a first response; an incorrect intervention can damage owned data.

89. Why might a balancer fail to resolve a badly skewed collection?

The balancer moves ranges subject to placement rules and resource constraints; it cannot split an indivisible range containing one repeated complete shard-key value. A large range or skewed workload therefore needs a key and capacity diagnosis, not simply more time.

If one tenant is the full key and holds most documents, moving that tenant moves the concentration rather than sharing it. Refinement with a useful suffix or resharding can address divisibility. Zone restrictions can independently prevent a desired placement.

Check range size, value frequency, migration failures, zone capacity and whether the observed skew is bytes or traffic. A balanced byte count does not imply balanced CPU demand. Treat manual range moves as controlled operational changes with evidence and monitoring.

90. How can a successful-looking write disappear after an election?

A write acknowledged under weaker durability settings may not have reached enough replica-set members before the primary loses leadership. If the new primary lacks that write, the former primary can roll it back during reconciliation.

An application that acknowledges an order to a customer after a primary-only acknowledgement has accepted a different failure exposure from an application requiring majority acknowledgement. The response contract must match the business consequence, including journaling and deployment configuration.

Majority acknowledgement reduces this election-related rollback exposure but does not eliminate application uncertainty after a network timeout. Separate evidence that a write committed from evidence that the client received its acknowledgement. Retry design still needs stable business identity and duplicate protection.

91. How do replication lag and the oplog window interact during recovery?

Replication lag is how far a secondary has fallen behind; the oplog window is how much operation history remains available for it to catch up. A secondary can recover by replay only while the needed history is still retained.

A member that is six hours behind cannot rely on an oplog currently retaining only four hours of required history. Increasing capacity after the history has already disappeared does not reconstruct those missing operations; recovery may require initial synchronization.

Monitor lag together with write volume, retention window and catch-up throughput. A burst can shrink the time represented by a size-limited oplog. Plan maintenance duration and recovery bandwidth using peak conditions, not only the normal daily average.

92. What should a change-stream consumer do when it cannot resume?

Classify the cause before retrying. An invalidation event and loss of the history needed by a resume token are different conditions. Persisting a token is necessary for recovery, but it cannot make expired history available again.

For a collection invalidation, startAfter can support starting a new stream after the invalidating event in supported cases; resumeAfter cannot resume past that event. If required history has been lost, the application needs a defined reconciliation or snapshot-and-catch-up procedure.

Checkpoint progress only in coordination with durable processing. Reopening a stream from a convenient current time can silently skip business changes. Monitor consumer lag against history retention, and test how recreated collections, snapshots and downstream deduplication interact.

93. Why should transaction callbacks avoid irreversible external effects?

Driver transaction helpers may retry a transaction callback after a transient failure. Database work can be retried within that protocol, while an email, payment request or third-party action performed inside the callback may already have occurred.

If a transaction records an order and calls a payment service before encountering a write conflict, rerunning the callback can issue the payment request again. A database rollback does not reverse an external system’s completed side effect.

Keep the transactional unit focused on database state, and durably record intent for external processing where appropriate. Use a stable operation identity and an external idempotency contract. A successful transaction plus a reliable delivery workflow is easier to reason about than pretending the external action participates in the database transaction.

94. Why can a long-running transaction fail despite low request throughput?

A transaction consumes resources while it remains open, so low request frequency does not make a large or slow transaction inexpensive. MongoDB 8.0 normally limits transaction lifetime to less than one minute; transactionLifetimeLimitSeconds controls the configured bound, and periodic cleanup aborts expired transactions. It is not an exact application cancellation timer.

A transaction that reads a large set, waits on a remote service and then writes many documents can retain state and create cache pressure while apparently doing little useful work. Excessive WiredTiger cache pressure can cause a write conflict; a transaction that cannot fit can fail with TransactionTooLargeForCache. Blindly rerunning the same oversized unit does not reduce its resource demand.

Move unrelated waiting outside the transaction and reduce its read/write footprint while preserving the required invariant. Splitting a transfer into independent commits is not acceptable if it removes essential atomicity. Inspect duration, contention and cache evidence before raising a lifetime limit; a larger bound can prolong pressure rather than fix the design. Explicitly abort abandoned work and follow the supported retry policy for the actual error.

95. When would you avoid a cross-shard transaction?

A cross-shard transaction is justified when the business invariant requires atomic changes across its participants. It also introduces coordination and failure exposure across those shards, so it should not substitute for examining whether the data belongs together.

An order and its tightly coupled reservation might be colocated by a suitable key, while a global reporting update can be derived asynchronously. That can reduce transaction scope without weakening the order’s essential invariant.

Compare latency, contention, failure recovery and data-model complexity under representative load. Do not replace an atomic requirement with eventual consistency merely for speed; explicitly define compensation and acceptable intermediate states when splitting the workflow.

96. How would you design a distributed counter with a clear consistency contract?

First decide whether readers require an exact current value or an eventually reconciled aggregate. A single atomically incremented document is simple but can become a hot write location; partitioned counters spread writes while making the read and reconciliation contract more complex.

For a display-only popularity count, summing partition contributions with bounded staleness may be acceptable. For a capacity limit that must never be exceeded, independently incrementing several partitions without an allocation protocol can violate the limit.

Retries need attention even when each increment is atomic: repeating an application request can increment twice. Associate effects with stable event identity or use an appropriate deduplication workflow. Distinguish atomic update semantics from exactly-once processing of external intent.

97. How would you investigate a query-plan regression affecting only some tenants?

Compare the same query shape across representative selectivities and tenant sizes. A plan that is efficient for a small tenant can examine many more keys or documents for a dominant tenant, even though the application sends structurally similar predicates.

Capture the actual predicates, indexes, execution statistics, server version and relevant plan-cache evidence. MongoDB explain does not simply replay the existing cached plan, so an explain result must be interpreted alongside evidence from the slow executions themselves.

Check for index changes, data skew and changed sort or projection requirements before applying a hint. A hint may stabilize one case while worsening another. Validate a proposed change against both small and large tenants and retain a rollback path rather than treating cache clearing as a permanent fix.

98. What can a hidden-index experiment prove?

A hidden index is maintained but unavailable to the query planner. Hiding one can test the read-performance consequence of its absence without immediately paying the cost of rebuilding it if the experiment must be reversed.

If hiding an index makes an important endpoint scan far more documents, that is evidence the index remains useful for that workload. If latency is unchanged, the conclusion is limited to the observed traffic and measurement period.

Observation when index is hidden

Supported conclusion

Not established

Read latency increases

Observed workload depended on planner access to the index

Every workload needs the index

Write throughput stays unchanged

Maintenance still occurs while hidden

Dropping would give no write benefit

Unique violation still rejected

Uniqueness remains enforced

Hidden means constraint disabled

Hidden indexes still consume storage and write-maintenance work, and unique constraints remain enforced. Therefore, hiding does not measure the write-throughput benefit of dropping an index. Plan changes and cache effects also need time and representative traffic before drawing conclusions.

99. Why can a compound multikey index fail to combine expected bounds?

Array predicates can refer to different elements unless the query explicitly requires the relevant conditions on the same element. MongoDB can combine certain multikey bounds when the query uses the appropriate $elemMatch structure for the indexed array paths.

For an array of line items, a condition on sku and another on quantity may match different line items. If the business question is whether one line item has both properties, express that same-element requirement rather than assuming the compound index changes the query’s meaning.

Check correctness before performance: rewriting with $elemMatch can change results as well as index bounds. Inspect execution statistics using representative arrays. Compound multikey indexes also restrict indexing multiple independent array fields in the same document; schema shape is part of index design.

100. How can a lookup pipeline unexpectedly multiply totals?

$lookup creates matching arrays; subsequent unwinding can produce several rows for each input document. Aggregating a parent-level amount after that expansion can count the same amount repeatedly.

An order worth 100 with three matching shipment records becomes three rows after unwind. Summing the order amount at that stage yields 300, even though the business value remains 100. Filtering or indexing the lookup can improve speed without correcting this grain mismatch.

Define the output grain and intended multiplicity first. Aggregate child information before joining, retain the parent array, or regroup using stable parent identity where appropriate. Reconcile parent counts and monetary totals before and after the join, including parents with no match.

101. How does time-series bucketing influence schema design?

Time-series collections group measurements into internal buckets using shared metadata and time. Stable metadata such as a sensor identity supports useful grouping; putting a rapidly changing measurement into metadata can fragment that grouping and reduce storage efficiency.

Choose granularity and metadata from actual arrival patterns and query windows. A temperature value belongs in the measurement, while a device or site identifier can describe its source. Out-of-order arrivals and sparse devices should be included in the evaluation.

The specialized collection is not interchangeable with a general mutable document store. MongoDB 8.0 has restrictions on updates, indexes and other operations. Confirm those restrictions before choosing it for a workload that frequently corrects historical measurements or requires unique measurement identifiers.

102. How should you reason about time-series expiration and corrections in MongoDB 8.0?

Time-series expiration is asynchronous and bucket-oriented. Data is not guaranteed to disappear at the exact expiration instant; a bucket becomes removable when its measurements have expired, and background removal introduces additional delay.

In MongoDB 8.0, time-series updates are restricted: they match and modify metadata, use update operators, update multiple documents and cannot upsert. A workflow that edits an arbitrary historical measurement cannot assume ordinary collection update behavior.

Partial TTL indexes supported since 7.0 can expire matching metadata groups sooner, but cannot extend retention beyond a shorter collection-level expiration. Separate business visibility rules from physical cleanup timing, and design corrections and retention changes against the documented collection restrictions.

103. When is a wildcard index a useful compromise?

A wildcard index can support queries over varying field names when the application genuinely has a flexible attribute model. It trades convenient coverage for index size and maintenance costs, and does not replace every carefully designed compound index.

A catalog with seller-defined attributes may benefit from indexing a bounded attributes subtree. Indexing every field across large documents can spend resources on values that are never queried. Frequently used filter-and-sort combinations may still justify dedicated indexes.

Evaluate supported query shapes and wildcard restrictions with execution statistics. Wildcard indexes are sparse, so missing-field queries need particular care. Treat unexpected growth in indexed paths as a schema-governance signal rather than allowing unbounded custom attributes to become an invisible operational cost.

104. How do you distinguish a core text index from MongoDB Search?

The core text index and $text query facility are different from MongoDB Search indexes and search operators. They have different capabilities, indexing configuration and operational requirements; sharing a text-search use case does not make them interchangeable.

A request for language analysis, relevance tuning or richer search behavior should be evaluated against the exact Search product and deployment support. For the MongoDB 8.0 baseline, verify what is available in the chosen managed or self-managed environment rather than copying examples from newer releases.

Compare relevance using a labeled query set, and include indexing lag and failure behavior in acceptance criteria. An ordinary database index does not automatically serve a Search query, and a Search rollout needs its own capacity and access-control review.

105. What must be established before choosing MongoDB Vector Search?

Establish deployment and version support, the embedding model contract, index requirements and the quality target. Vector similarity is a retrieval mechanism; it does not establish that returned documents are factually correct or authorized for the requester.

An embedding-model change can alter dimensions and similarity behavior, requiring a planned re-embedding and index transition. Compare retrieval quality with a representative labeled set and include tenant or authorization filtering in the actual query design.

Approximate nearest-neighbor retrieval trades search effort against recall and latency. Measure these together rather than treating a fast response as sufficient. Do not present current Search capabilities as universally available in every MongoDB 8.0 deployment or as permanently exclusive to one hosting model.

106. What threat boundaries remain with Queryable Encryption?

Queryable Encryption can protect selected values from the database server while permitting supported queries through properly configured clients. It does not protect plaintext from an application endpoint that is authorized to decrypt it, nor remove the need for authentication, access control and transport security.

If an attacker compromises the application and obtains usable key access, encrypting the database field does not prevent that application from revealing the value. Key separation, endpoint security and credential lifecycle are therefore part of the design.

Evaluate the documented threat model rather than promising protection against every observer or persistent compromise. Queryable Encryption also changes diagnostics and performance characteristics. Plan support procedures that avoid restoring sensitive plaintext to logs merely to make troubleshooting easier.

107. How do encrypted-field query restrictions affect data modeling?

Choose an encryption approach from the required operations as well as the sensitivity of the data. Queryable Encryption and client-side field-level encryption support different operations and have version-specific restrictions; an encrypted field is not an ordinary indexed field with invisible implementation details.

For MongoDB 8.0 Queryable Encryption, review supported equality and range configurations, types and collection restrictions before committing the model. Unsupported sorting, aggregation or indexing requirements may require a different representation or workflow rather than a query rewrite alone.

Avoid adding an unprotected duplicate of a sensitive value solely to recover convenient queries. Any derived search field needs its own leakage assessment. Validate the complete client, driver, encryption library and key-management combination, including rotation and restoration of historical data.

108. How would you choose between shared and isolated tenant storage?

Compare the required isolation boundary, tenant scale, operational cost and failure blast radius. A tenantId field in a shared collection enables logical partitioning, but it does not itself enforce authorization or reserve resources for each tenant.

A shared design needs consistent tenant scoping across reads, updates, aggregations and background jobs. Separate databases or deployments can simplify some boundaries while increasing operational work and connection management. Database separation alone does not guarantee independent compute capacity.

Test tenant escape paths, noisy-neighbor behavior and tenant-specific restoration requirements. A design that makes routine queries easy may make restoring one customer difficult. Choose an isolation model that the application and operating team can enforce across the full lifecycle.

109. How do you investigate a hot tenant without blaming the shard count?

Identify whether the tenant dominates request rate, document size, transaction contention or a particular aggregation. Then map that workload to the shard-key ranges and actual shard resources involved.

A tenant with few documents may still saturate a shard through repeated expensive queries. Conversely, a very large but quiet tenant can dominate storage without causing current CPU pressure. Adding shards helps only if the key and workload can use them.

Compare tenant-scoped latency, keys examined, bytes read and write contention over the same interval. Potential responses include query correction, admission control, a more divisible key or stronger workload isolation. Recheck the tenant’s service objective after the change rather than using cluster-average latency as the success measure.

110. What evidence proves that point-in-time recovery is usable?

A backup schedule proves that backup work was planned; a timed restoration with application reconciliation proves much more about recoverability. Point-in-time recovery additionally depends on continuous required history and a supported recovery procedure for the deployment.

Restore to an isolated environment at a chosen point before a known bad change. Verify key availability, users and configuration, collection and index state, and business invariants such as order-to-payment reconciliation. Record both the recovered point and the time until the application is usable.

Do not substitute a live replica for historical recovery: destructive changes can replicate. Include the loss of the original environment and credentials in the rehearsal. Recovery objectives should cover reconnecting dependent services and handling external effects that cannot be rolled back with the database.

111. Why separate a binary upgrade from raising feature compatibility version?

Binary version and feature compatibility version serve different purposes. During a supported upgrade, newer binaries can run before enabling persistent features that are incompatible with the previous version, allowing a deliberate validation interval.

For an 8.0 upgrade, follow the topology-specific supported sequence and driver compatibility requirements. Mixed-version operation is a transitional state with restrictions, not a permanent target architecture. Validate representative reads, writes and operational tooling before raising FCV.

Raising FCV can enable features that complicate a return to the prior version. Record approval criteria, backups and the exact supported recovery path before that step. A successful process restart alone is insufficient evidence that the application and operational ecosystem are ready.

112. Why is downgrade planning different from rolling back an application release?

A database downgrade must account for persisted feature compatibility, storage and metadata state, and supported binary paths. Replacing a binary with an older one is not equivalent to restoring an earlier application container.

For the MongoDB 8.0 baseline, binary downgrades are not supported for Community Edition. Enterprise binary downgrade requires assistance from MongoDB support. Do not infer an independently supported downgrade path from the existence of an FCV command or newer-version documentation. Identify incompatible persisted features and the deployment-specific recovery procedure before an upgrade.

Compare a supported downgrade with restoring a pre-upgrade backup and replaying an approved data path. The latter can also lose or require reconciling post-upgrade writes. Set the decision point and recovery budget before upgrading so that production pressure does not force an improvised reversal.

113. How do you prevent a connection storm after a service restart?

Bound connection pools and concurrent application work, reuse clients appropriately, and stagger recovery so many processes do not all create maximum pools at once. Pool capacity is a fleet-level calculation, not merely a per-process preference.

If 100 application instances each allow 100 connections to a server, the configured potential is already 10,000 before other clients and topology effects. Increasing pool sizes can amplify pressure while hiding the actual slow-query or queueing cause.

Observe connection establishment, pool checkout waits, server selection and request latency separately. Use bounded queues, backoff with jitter and load shedding where the service contract permits. A larger pool does not create more database CPU or disk throughput.

114. How do WiredTiger cache and operating-system memory interact?

WiredTiger uses an internal cache, while the operating system also uses memory for filesystem caching and the process needs memory outside that cache. Consequently, configuring the cache to consume nearly all available memory can make the deployment less stable.

A high cache occupancy alone is not proof of a problem. Correlate eviction work, dirty data, read latency, page activity and host memory pressure with workload changes. In containers, ensure the effective resource limits are understood rather than reasoning from the physical host’s total memory.

Index growth or a changed working set can increase reads even without a traffic increase. Adjust cache settings only with evidence and headroom for the rest of the process and operating system. Investigate inefficient queries before treating memory allocation as the sole solution.

115. Why can storage grow much faster than logical document size?

Physical storage includes indexes, storage-engine structures, journal and replication-related files, and temporary operational headroom. Compression and allocation behavior mean the sum is not a fixed multiplier of application JSON size.

Adding several indexes to a write-heavy collection increases both persistent storage and maintenance work. Index builds, resharding or backup workflows can require extra space precisely when the system is busiest; planning only for the final document total misses that peak.

Measure collection and index growth alongside free-space trends and operational events. Deleting documents does not necessarily return all allocated filesystem space immediately. Capacity planning should distinguish reusable internal space from space actually returned to the filesystem.

116. How do server time limits differ from client timeouts for uncertain writes?

A server operation time limit, write-concern timeout, server-selection timeout and client network timeout constrain different stages. A client ceasing to wait does not prove that a write never committed, and a write-concern timeout does not undo an already applied modification.

If a request times out after sending an order update, retrying with a new business identifier can duplicate intent. Reconcile using stable identity and the supported driver retry semantics instead of translating every timeout into a confirmed failure.

Limit

What it constrains

What a timeout does not prove

Server execution limit

Supported operation execution

That every earlier effect was reversed

Write-concern timeout

Waiting for requested acknowledgement

That the primary did not apply the write

Client network timeout

Client waiting for a response

That the server did not commit

Set an end-to-end budget that includes queueing, selection, execution and acknowledgement. Interpret the actual error and operation type before deciding what to retry. maxTimeMS is a server execution control with operation-specific behavior, not a universal distributed cancellation guarantee.

117. How does an outbox help connect MongoDB transactions to external delivery?

An outbox stores the business change and a delivery-intent record in the same transaction where supported. A separate worker or change-stream consumer delivers that intent, avoiding a gap between committing the change and remembering that an external action is needed.

The worker can still crash after the external system accepts an event but before the worker records success. Therefore, delivery is not automatically exactly once: the receiver needs a stable event identifier and a deduplication or idempotency contract.

Retain enough outbox and stream history for recovery, and reconcile stuck records independently of the live stream. Keep delivery status transitions auditable. A change stream is a useful notification mechanism, but it does not replace a durable business definition of what remains undelivered.

118. How should deletion, retention and legal holds interact operationally?

Define the applicable retention and hold policy with the responsible owners, then implement data lifecycle behavior that follows it. A TTL index is an asynchronous deletion mechanism; it does not understand every exception or establish policy compliance by itself.

If some records are subject to an approved hold, a blanket expiration rule can conflict with the intended lifecycle. Design explicit eligibility and protected handling rather than depending on an operator to race the TTL monitor.

Include replicas, backups, exports, search indexes and downstream systems in the inventory. Restoring an older backup can reintroduce previously deleted records, so recovery procedures need reconciliation. Record evidence and exceptions according to policy without making universal legal claims about a technical setting.

119. Does change-stream updateLookup return the document exactly as it was after that event?

No. fullDocument: "updateLookup" retrieves the current majority-committed document when the lookup is performed. That can include a later committed update, so it is not an event-time snapshot. A deleted document can also make the lookup return null.

Suppose one update changes an order from queued to packed, and a later update changes it to shipped before the consumer’s lookup. The earlier event can describe the packed transition while its looked-up full document already says shipped. That may suit a consumer converging a search index toward current state, but it is unsuitable as proof of the exact historical state after each event.

When exact pre- or post-images are required, enable the collection’s change-stream pre/post-image support before the relevant changes and select supported options such as whenAvailable or required. The former can return an unavailable image as null; the latter errors if the requested image is unavailable. Plan image retention and storage cost alongside consumer lag. These options do not recover images that were never captured or have expired, and the consumer still needs durable progress and replay handling.

120. What evidence should you capture before mitigating a MongoDB incident?

Capture a time-bounded picture of the symptom, topology, recent changes and resource state before applying a disruptive remedy. Useful evidence includes affected query shapes, error labels, replication or routing state and host or service metrics collected over the same interval.

If latency rose after a deployment, compare request volume and query behavior before assuming a database regression. A connection surge, index change and replication issue call for different mitigations even when the user-visible symptom is identical.

Choose a reversible mitigation with an owner, expected signal and rollback condition. Preserve necessary evidence without collecting sensitive payloads indiscriminately. After stabilization, verify business correctness and backlog recovery; a lower latency graph alone does not prove that failed or uncertain operations were resolved.

MongoDB Documentation and Further Reading

These official MongoDB references use the version 8.0 documentation view. Check the deployed server’s patch level, feature compatibility version, driver and service capabilities when applying an example. Atlas Search, Vector Search and encryption features have additional deployment and version requirements.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts