MCQs Of Day 8: MongoDB CRUD Operations – Part 4 (Delete)
1. Which method is used to delete a single document from a collection in MongoDB?
A) delete()
B) deleteMany()
C) deleteOne()
D) remove()
Answer: C) deleteOne()
Explanation: The deleteOne() method removes the first document that matches the query criteria.
2. What is the purpose of the deleteMany() method in MongoDB?
A) To delete all documents from a collection.
B) To delete a single document based on a condition.
C) To delete multiple documents matching the criteria.
D) To drop the entire collection.
Answer: C) To delete multiple documents matching the criteria.
Explanation: The deleteMany() method removes all documents that match the filter criteria.
3. What happens if the filter in deleteOne() matches multiple documents?
A) All matching documents are deleted.
B) Only the first matching document is deleted.
C) An error is thrown.
D) No documents are deleted.
Answer: B) Only the first matching document is deleted.
Explanation: The deleteOne() method deletes only the first document that matches the filter.
4. How can you delete all documents in a collection?
A) Use deleteAll()
B) Use deleteOne({})
C) Use deleteMany({})
D) Use remove({})
Answer: C) Use deleteMany({})
Explanation: Passing an empty filter {} to deleteMany() deletes all documents in the collection.
5. What is returned by the deleteOne() method?
A) Number of documents deleted.
B) An object with deletion details.
C) The deleted document.
D) Nothing.
Answer: B) An object with deletion details.
Explanation: Both deleteOne() and deleteMany() return an object containing the number of documents deleted.
Intermediate Questions
6. What does the deletedCount field in the result object represent?
A) The number of documents updated.
B) The number of documents inserted.
C) The number of documents deleted.
D) The number of matching documents.
Answer: C) The number of documents deleted.
Explanation: The deletedCount field specifies how many documents were removed during the delete operation.
7. Which operator is used to match documents where a field is missing?
A) $missing
B) $exists
C) $notExist
D) $absent
Answer: B) $exists
Explanation: The $exists operator is used to check for the existence or absence of a field.
8. How would you delete documents with an _id field equal to a specific ObjectId?
A) Use db.collection.deleteById()
B) Use db.collection.deleteMany({ _id: "id_value" })
C) Use db.collection.deleteOne({ _id: ObjectId("id_value") })
D) Use db.collection.deleteOne({ id: "id_value" })
Answer: C) Use db.collection.deleteOne({ _id: ObjectId("id_value") })
Explanation: The _id field must be matched with an ObjectId instance when querying.
9. What happens if you use deleteMany() with no filter?
A) An error is thrown.
B) No documents are deleted.
C) All documents in the collection are deleted.
D) Only one document is deleted.
Answer: C) All documents in the collection are deleted.
Explanation: An empty filter {} matches all documents.
10. How do you ensure no accidental deletions when using deleteMany()?
A) Use a find() query first.
B) Use a non-empty filter.
C) Both A and B.
D) It is not possible to prevent accidental deletions.
Answer: C) Both A and B.
Explanation: Always use a find() query to confirm the filter and ensure the filter is not empty.
Advanced Scenarios
11. How do you delete documents where a nested field matches a value?
A) { nested_field.value: "value" }
B) { "nested_field.value": "value" }
C) { "nested_field": { value: "value" } }
D) { nested_field: { value: "value" } }
Answer: B) { "nested_field.value": "value" }
Explanation: To access a field inside an embedded document, use dot notation.
12. What is the default behavior of deleteOne() if no document matches the filter?
A) Deletes the first document in the collection.
B) Deletes all documents.
C) Does nothing.
D) Throws an error.
Answer: C) Does nothing.
Explanation: If no document matches the filter, the method exits without any deletions.
13. Can you use aggregation pipelines in delete queries in MongoDB?
A) Yes, but only with deleteOne().
B) Yes, but only with deleteMany().
C) Yes, with both methods.
D) No, aggregation pipelines cannot be used in delete queries.
Answer: D) No, aggregation pipelines cannot be used in delete queries.
Explanation: MongoDB's delete operations do not support aggregation pipelines.
14. Which operator can you use to delete documents with a range condition?
A) $range
B) $gt and $lt
C) $in
D) $eq
Answer: B) $gt and $lt
Explanation: $gt (greater than) and $lt (less than) are used to specify ranges in filters.
Scenario-Based Questions
15. How would you delete all products with a price below 50?
A) db.products.deleteOne({ price: { $lt: 50 } })
B) db.products.deleteMany({ price: { $lt: 50 } })
C) db.products.deleteOne({ price < 50 })
D) db.products.deleteMany({ price < 50 })
Answer: B) db.products.deleteMany({ price: { $lt: 50 } })
Explanation: The $lt operator is used with deleteMany() to delete all matching documents.
Expanding the MCQs
The above format can be repeated and expanded with different scenarios and filters, such as:
- Deleting based on multiple conditions (AND, OR).
- Using operators like $gte, $lte, $ne, $in, $nin.
- Deleting based on the absence of fields ($exists).
- Questions involving error handling and edge cases.
If you’d like, I can continue with the next set of 85 MCQs or focus on specific subtopics within MongoDB delete operations. Let me know!
4o
You said:
yes
ChatGPT said:
ChatGPT
Here’s the continuation of the MCQs on MongoDB Delete Operations:
16. What happens if deleteOne() is called on an empty collection?
A) The first document is deleted.
B) An error is thrown.
C) Nothing happens.
D) A new document is created.
Answer: C) Nothing happens.
Explanation: If the collection is empty, no matching document is found, and no action is taken.
17. How do you delete documents where a field contains any value within a specified array?
A) Use $all
B) Use $in
C) Use $contains
D) Use $array
Answer: B) Use $in
Explanation: The $in operator matches documents where the specified field's value matches any value in the given array.
18. To delete documents where the status field is either inactive or pending, what query should you use?
A) { status: { $eq: "inactive", $eq: "pending" } }
B) { status: { $or: ["inactive", "pending"] } }
C) { $or: [{ status: "inactive" }, { status: "pending" }] }
D) { status: { $in: ["inactive", "pending"] } }
Answer: D) { status: { $in: ["inactive", "pending"] } }
Explanation: The $in operator simplifies queries where a field can match multiple possible values.
19. How do you delete documents based on a regex pattern in a field?
A) { field: { $regex: /pattern/ } }
B) { field: { $pattern: "regex" } }
C) { field: { $matches: /pattern/ } }
D) { field: "regex" }
Answer: A) { field: { $regex: /pattern/ } }
Explanation: The $regex operator matches documents where the field value matches the specified regular expression.
20. To delete all documents in the collection users where the age is greater than or equal to 30, what query is correct?
A) db.users.deleteMany({ age: { $lte: 30 } })
B) db.users.deleteMany({ age: { $gte: 30 } })
C) db.users.deleteOne({ age: { $gte: 30 } })
D) db.users.deleteMany({ age > 30 })
Answer: B) db.users.deleteMany({ age: { $gte: 30 } })
Explanation: The $gte operator is used for conditions where the value is greater than or equal to a specified number.
Operators and Edge Cases
21. Which of the following is a valid use of the $and operator in a delete query?
A) { $and: { field1: "value1", field2: "value2" } }
B) { $and: [{ field1: "value1" }, { field2: "value2" }] }
C) { $and: { field1: { $eq: "value1" }, field2: { $eq: "value2" } } }
D) { field1: { $and: "value1" }, field2: { $and: "value2" } }
Answer: B) { $and: [{ field1: "value1" }, { field2: "value2" }] }
Explanation: The $and operator requires an array of conditions to match.
22. Can you use $or and $not operators together in a delete query?
A) Yes, by nesting them appropriately.
B) No, they cannot be used together.
C) Yes, but only with deleteMany().
D) No, they only work with find() queries.
Answer: A) Yes, by nesting them appropriately.
Explanation: $or and $not can be combined in a filter using logical nesting.
23. If you want to delete all documents where a field is either null or does not exist, which query should you use?
A) { field: { $eq: null } }
B) { field: null }
C) { $or: [{ field: { $eq: null } }, { field: { $exists: false } }] }
D) { field: { $exists: null } }
Answer: C) { $or: [{ field: { $eq: null } }, { field: { $exists: false } }] }
Explanation: The combination of $eq and $exists ensures matching both null and non-existent fields.
24. What will happen if deleteMany({ field: { $in: [] } }) is executed?
A) Deletes all documents.
B) Deletes no documents.
C) Throws an error.
D) Deletes documents with an empty array in the field.
Answer: B) Deletes no documents.
Explanation: An empty $in array matches nothing, so no documents are deleted.
25. Can you delete documents based on the size of an array field?
A) Yes, using the $size operator.
B) No, array size cannot be used in delete queries.
C) Yes, but only with deleteOne().
D) Yes, using $count.
Answer: A) Yes, using the $size operator.
Explanation: The $size operator matches documents based on the length of an array field.
Practical Scenarios and Advanced Use Cases
26. How can you delete documents where the field score is not between 50 and 100?
A) { score: { $not: { $gte: 50, $lte: 100 } } }
B) { score: { $not: [{ $gte: 50 }, { $lte: 100 }] } }
C) { score: { $or: [{ $lt: 50 }, { $gt: 100 }] } }
D) { score: { $not: [50, 100] } }
Answer: C) { score: { $or: [{ $lt: 50 }, { $gt: 100 }] } }
Explanation: $or is used to match documents outside the specified range.
27. How would you delete documents that match one of two field values using deleteOne()?
A) { field: { $or: ["value1", "value2"] } }
B) { $or: [{ field: "value1" }, { field: "value2" }] }
C) { field: { $in: ["value1", "value2"] } }
D) { $or: ["value1", "value2"] }
Answer: B) { $or: [{ field: "value1" }, { field: "value2" }] }
Explanation: $or requires individual conditions for each field value.
I’ll continue in this format to complete 100 MCQs. Let me know if you’d like to focus on specific cases or techniques!
4o
You said:
yes
ChatGPT said:
ChatGPT
Continuing with the MCQs on MongoDB Delete Operations, here are more questions to extend the list:
Complex Scenarios
28. What happens if you call deleteOne() with an empty filter object ({})?
A) Deletes one random document.
B) Deletes the first document in the collection.
C) Deletes all documents in the collection.
D) Throws an error.
Answer: B) Deletes the first document in the collection.
Explanation: An empty filter matches all documents, but deleteOne() removes only the first matching document.
29. If a document matches multiple conditions in deleteMany(), how many times is it deleted?
A) Once
B) Twice
C) As many times as it matches the conditions
D) Depends on the conditions
Answer: A) Once
Explanation: A document can only be deleted once, even if it matches multiple conditions.
30. What does the { collation: { locale: "en", strength: 2 } } option do in a delete operation?
A) Deletes documents based on case-sensitive matches.
B) Deletes documents ignoring case differences.
C) Deletes documents only with exact field matches.
D) Deletes documents using regular expressions.
Answer: B) Deletes documents ignoring case differences.
Explanation: Collation options control case and locale-specific string matching.
31. To delete documents where an array field contains more than 5 elements, which operator is used?
A) $size
B) $gt
C) $elemMatch
D) $exists
Answer: A) $size
Explanation: The $size operator matches documents based on the length of an array.
32. Can you use the _id field to delete a specific document?
A) Yes, always.
B) No, _id cannot be used in delete queries.
C) Yes, but only with deleteMany().
D) Yes, but _id must be a string.
Answer: A) Yes, always.
Explanation: The _id field is unique for each document, making it ideal for targeting specific documents.
Query Optimization
33. What is the purpose of an index in a delete operation?
A) Ensures multiple documents are deleted.
B) Speeds up matching documents for deletion.
C) Prevents deletion of indexed fields.
D) Allows deletion of non-indexed fields.
Answer: B) Speeds up matching documents for deletion.
Explanation: Indexes improve the efficiency of finding documents to delete.
34. What happens if a compound index is used in a delete query?
A) Deletes only documents matching all indexed fields.
B) Deletes documents matching any field in the index.
C) Compound indexes cannot be used in delete queries.
D) Deletes all documents in the indexed collection.
Answer: A) Deletes only documents matching all indexed fields.
Explanation: Compound indexes match documents where all specified fields satisfy the conditions.
35. How can you delete documents matching a nested field condition?
A) { "field.subfield": value }
B) { field.subfield: value }
C) { "field: { subfield: value } }
D) { field: { subfield: value } }
Answer: A) { "field.subfield": value }
Explanation: Dot notation is used to reference nested fields in MongoDB.
36. Which of the following is correct for deleting a document with an embedded document field?
A) { field: { $eq: { key: value } } }
B) { field: { key: value } }
C) { "field.key": value }
D) { "field": { key: value } }
Answer: D) { "field": { key: value } }
Explanation: Embedded documents must match the exact structure and content provided in the query.
37. Can you delete documents based on a field's data type?
A) Yes, using the $type operator.
B) No, MongoDB does not support data-type-based deletion.
C) Yes, using $dataType.
D) Yes, but only for numeric fields.
Answer: A) Yes, using the $type operator.
Explanation: The $type operator matches documents based on the BSON data type of a field.
Performance Considerations
38. What effect does using justOne: true in a remove() query have?
A) Deletes all matching documents.
B) Deletes only the first matching document.
C) Deletes one document randomly.
D) Prevents the deletion of indexed documents.
Answer: B) Deletes only the first matching document.
Explanation: The justOne option limits the operation to the first matching document.
39. If a deleteMany() operation is taking too long, what can you do?
A) Add an index on the filter field.
B) Use deleteOne() instead.
C) Drop the collection.
D) Restart the MongoDB server.
Answer: A) Add an index on the filter field.
Explanation: Indexes improve query performance by reducing the time to find matching documents.
40. What happens if a delete operation times out?
A) The operation retries automatically.
B) All matched documents are deleted.
C) No documents are deleted.
D) Partially matched documents are deleted.
Answer: C) No documents are deleted.
Explanation: If a delete operation times out, it is aborted without making changes to the collection.
Let me know if you'd like me to complete up to 100 MCQs with further topics, such as edge cases, advanced queries, or MongoDB-specific syntax rules!
4o
You said:
yes
ChatGPT said:
ChatGPT
Continuing with the MCQs on MongoDB Delete Operations, here are additional questions to extend the list:
Advanced Features
41. Which of the following scenarios would require the use of the writeConcern option during a delete operation?
A) Ensuring all documents are deleted from a collection.
B) Controlling the acknowledgment of delete operations.
C) Preventing the deletion of read-only fields.
D) Ensuring the deletion of indexed documents only.
Answer: B) Controlling the acknowledgment of delete operations.
Explanation: The writeConcern option determines the level of acknowledgment the server provides for the delete operation.
42. Can a delete operation specify a condition with both $and and $or operators?
A) Yes, as long as the conditions are nested correctly.
B) No, only one logical operator is allowed per query.
C) Yes, but only with deleteOne().
D) No, these operators are not supported in delete queries.
Answer: A) Yes, as long as the conditions are nested correctly.
Explanation: MongoDB supports combining $and and $or operators in a query using proper nesting.
43. How does the hint option optimize delete operations?
A) Deletes all documents with hints.
B) Forces the query to use a specific index.
C) Prevents deletion of indexed fields.
D) Automatically selects the fastest index.
Answer: B) Forces the query to use a specific index.
Explanation: The hint option forces the query to use a specified index for better performance.
44. Can you use the $regex operator in a delete filter?
A) Yes, for matching string patterns in fields.
B) No, $regex is not supported in delete queries.
C) Yes, but only with deleteMany().
D) No, $regex can only be used in update queries.
Answer: A) Yes, for matching string patterns in fields.
Explanation: The $regex operator matches string patterns and can be used in delete filters.
45. What happens if you try to delete a document in a sharded cluster without specifying the shard key?
A) The operation fails.
B) The operation succeeds on all shards.
C) The operation deletes a random document.
D) The operation only affects the primary shard.
Answer: A) The operation fails.
Explanation: In a sharded cluster, the shard key is required to route the delete operation to the appropriate shard.
Best Practices
46. Why should caution be exercised when using {} as a filter in deleteMany()?
A) It results in a syntax error.
B) It deletes all documents in the collection.
C) It locks the database.
D) It only works with capped collections.
Answer: B) It deletes all documents in the collection.
Explanation: An empty filter matches all documents, so deleteMany() will remove all documents.
47. What is the recommended way to ensure safe deletions in production environments?
A) Test the query using find() before deleting.
B) Always use deleteMany() instead of deleteOne().
C) Delete documents in bulk.
D) Avoid using filters in delete operations.
Answer: A) Test the query using find() before deleting.
Explanation: Using find() allows you to verify the query results before applying the delete operation.
48. Can you use aggregation pipelines with delete operations?
A) No, aggregation pipelines are not supported in delete queries.
B) Yes, but only with deleteMany().
C) Yes, but they must be used with $match.
D) No, aggregation pipelines are only for find() and update().
Answer: A) No, aggregation pipelines are not supported in delete queries.
Explanation: Aggregation pipelines are exclusive to find() and update() operations.
Error Handling
49. What error is thrown if the deleteMany() query has an invalid syntax?
A) SyntaxError
B) MongoParseError
C) MongoError
D) InvalidQueryError
Answer: C) MongoError
Explanation: MongoDB operations, including deleteMany(), throw a MongoError for invalid syntax.
50. How can you log deleted documents for auditing purposes?
A) Use the auditLogs collection.
B) Enable logging in the MongoDB server.
C) Manually query and store the documents before deletion.
D) MongoDB automatically stores deleted documents in a log.
Answer: C) Manually query and store the documents before deletion.
Explanation: MongoDB does not log deleted documents by default; you must store them manually.
Let me know if you'd like the list to reach 100 with a focus on edge cases, advanced operations, or more practice scenarios!
4o
You said:
yes
ChatGPT said:
ChatGPT
Here are MCQs 51–100 on MongoDB delete operations to complete the set:
Advanced Query Operations
51. Which operator is used to delete documents with a value not equal to a specified value?
A) $gt
B) $lt
C) $ne
D) $eq
Answer: C) $ne
Explanation: The $ne operator is used to filter documents where the field value is not equal to the specified value.
52. Can the $exists operator be used in a delete query?
A) Yes, to check if a field exists or not.
B) No, it is not valid in delete operations.
C) Yes, but only for indexed fields.
D) No, it is exclusive to aggregation queries.
Answer: A) Yes, to check if a field exists or not.
Explanation: The $exists operator can filter documents where a field exists or is missing.
53. What happens if you omit the filter parameter in deleteMany()?
A) All documents are deleted.
B) An error is thrown.
C) Only one document is deleted.
D) The operation has no effect.
Answer: B) An error is thrown.
Explanation: The filter parameter is mandatory. An omission results in an error.
54. Which MongoDB method would you use to delete documents older than a specific date?
A) deleteByDate()
B) deleteMany() with $lt
C) removeByDate()
D) deleteOne() with $ne
Answer: B) deleteMany() with $lt
Explanation: The $lt operator filters documents with dates earlier than the specified value.
**55. What will the following query do?
javascript
CopyEdit
db.orders.deleteOne({ status: { $in: ["shipped", "delivered"] } });
```**
A) Deletes all documents with the status "shipped" or "delivered."
B) Deletes one document with the status "shipped" or "delivered."
C) Deletes the first document in the collection.
D) Deletes documents with the status not in ["shipped", "delivered"].
**Answer:** B) Deletes one document with the status "shipped" or "delivered."
**Explanation:** The `$in` operator matches either value, and `deleteOne()` removes the first matching document.
---
**56. How can you ensure a delete query matches a numeric field greater than 100?**
A) Use `$lt` operator.
B) Use `$eq` operator.
C) Use `$gt` operator.
D) Use `$gte` operator.
**Answer:** C) Use `$gt` operator.
**Explanation:** The `$gt` operator matches values greater than the specified number.
---
### **Index and Performance**
**57. Which index improves the performance of delete queries?**
A) Sparse index
B) Compound index
C) Text index
D) Any index
**Answer:** D) Any index
**Explanation:** Indexes in general optimize query execution, including delete operations.
---
**58. How does MongoDB handle deletion in capped collections?**
A) Allows manual deletions with `deleteMany()`.
B) Does not allow deletion of individual documents.
C) Supports `deleteOne()` only.
D) Deletes all documents automatically.
**Answer:** B) Does not allow deletion of individual documents.
**Explanation:** Capped collections have fixed sizes and do not permit individual document deletions.
---
**59. Which parameter can you use to bypass validation during a delete operation?**
A) `validate`
B) `bypassDocumentValidation`
C) `ignoreValidation`
D) `noValidate`
**Answer:** B) `bypassDocumentValidation`
**Explanation:** This parameter skips document validation rules during operations.
---
**60. When running a `deleteMany()` query, how is the query distributed in a sharded cluster?**
A) Evenly across all shards.
B) Based on the primary shard only.
C) Based on the shard key.
D) Randomly across shards.
**Answer:** C) Based on the shard key.
**Explanation:** MongoDB routes queries to the appropriate shards using the shard key.
---
### **Edge Cases**
**61. If the `filter` parameter matches no documents, what happens during a `deleteMany()` operation?**
A) An error is thrown.
B) No documents are deleted.
C) A random document is deleted.
D) All documents are deleted.
**Answer:** B) No documents are deleted.
**Explanation:** If no documents match the filter, the operation has no effect.
---
**62. What does the following query do?
```javascript
db.users.deleteMany({ age: { $exists: false } });
```**
A) Deletes documents where the `age` field does not exist.
B) Deletes documents where the `age` field exists.
C) Deletes all documents.
D) Throws an error.
**Answer:** A) Deletes documents where the `age` field does not exist.
**Explanation:** The `$exists: false` filter matches documents without the `age` field.
---
**63. How can you delete multiple documents while limiting the deletion to 100 documents?**
A) Use `deleteMany()` with a `limit` parameter.
B) Use a combination of `find()` and `deleteOne()`.
C) Use `deleteMany()` with `$limit`.
D) MongoDB does not support limiting delete operations.
**Answer:** D) MongoDB does not support limiting delete operations.
**Explanation:** The `deleteMany()` method does not allow setting a limit on deletions directly.
---
### **Error Handling**
**64. What does the `acknowledged` field in a delete result indicate?**
A) Whether the operation succeeded.
B) The number of documents deleted.
C) The status of the database connection.
D) Whether the filter was valid.
**Answer:** A) Whether the operation succeeded.
**Explanation:** The `acknowledged` field shows if the server acknowledged the delete operation.
---
**65. What happens if you run a delete operation on a non-existent collection?**
A) The collection is created and then deleted.
B) An error is thrown.
C) The operation succeeds without effect.
D) The operation fails silently.
**Answer:** C) The operation succeeds without effect.
**Explanation:** MongoDB does not throw errors when deleting from non-existent collections.
---
Let me know if you'd like even more focused MCQs or further breakdowns for certain areas!
4o
You said:
yes
ChatGPT said:
ChatGPT
Here are MCQs 66–100 focusing on advanced concepts, scenarios, and edge cases for MongoDB deleteOne() and deleteMany() operations:
Behavioral Scenarios
66. What happens if deleteMany() is run with an empty filter?
A) Deletes all documents in the collection.
B) Deletes no documents.
C) Throws an error.
D) Deletes only one document.
Answer: A) Deletes all documents in the collection.
Explanation: An empty filter matches every document, and deleteMany() removes all of them.
67. Which method is more efficient for deleting a single document?
A) deleteOne()
B) deleteMany()
C) Both are equally efficient.
D) It depends on the document size.
Answer: A) deleteOne()
Explanation: deleteOne() is optimized for removing a single document, making it faster in this scenario.
**68. What does the following command achieve?
javascript
CopyEdit
db.logs.deleteMany({ timestamp: { $gte: new Date("2025-01-01") } });
```**
A) Deletes logs older than January 1, 2025.
B) Deletes logs created on or after January 1, 2025.
C) Deletes all logs in the collection.
D) Throws a syntax error.
**Answer:** B) Deletes logs created on or after January 1, 2025.
**Explanation:** The `$gte` operator matches dates greater than or equal to the specified value.
---
**69. How do you delete documents where a nested field matches a condition?**
A) Use the `path` operator.
B) Use dot notation in the filter.
C) Use the `$nested` operator.
D) MongoDB does not support nested field deletions.
**Answer:** B) Use dot notation in the filter.
**Explanation:** Dot notation allows targeting nested fields in documents.
---
**70. What happens when a delete query is issued without proper write permissions?**
A) The operation succeeds silently.
B) The operation is ignored.
C) An authorization error is thrown.
D) The database shuts down.
**Answer:** C) An authorization error is thrown.
**Explanation:** MongoDB enforces role-based access control, preventing unauthorized operations.
---
### **Practical Applications**
**71. How can you delete documents with an empty array as a value?**
A) `{ field: { $empty: true } }`
B) `{ field: { $size: 0 } }`
C) `{ field: { $exists: false } }`
D) `{ field: { $eq: [] } }`
**Answer:** B) `{ field: { $size: 0 } }`
**Explanation:** The `$size` operator matches arrays of a specific length.
---
**72. How can you delete documents with a field containing null values?**
A) `{ field: { $null: true } }`
B) `{ field: null }`
C) `{ field: { $exists: false } }`
D) `{ field: { $type: "null" } }`
**Answer:** B) `{ field: null }`
**Explanation:** A filter with `null` matches fields explicitly set to `null` or missing entirely.
---
**73. What would the following query achieve?
```javascript
db.customers.deleteOne({ purchases: { $exists: false } });
```**
A) Deletes customers with the `purchases` field missing.
B) Deletes customers with empty `purchases`.
C) Deletes all customers.
D) Deletes customers where `purchases` equals null.
**Answer:** A) Deletes customers with the `purchases` field missing.
**Explanation:** `$exists: false` matches documents without the specified field.
---
**74. What does the following query do?
```javascript
db.inventory.deleteMany({ $or: [{ qty: 0 }, { status: "obsolete" }] });
```**
A) Deletes documents with both conditions.
B) Deletes documents with either condition.
C) Deletes only one matching document.
D) Throws a syntax error.
**Answer:** B) Deletes documents with either condition.
**Explanation:** The `$or` operator matches documents meeting at least one of the criteria.
---
### **Error Handling and Special Cases**
**75. What does the `deletedCount` field in a delete result represent?**
A) Number of documents matched.
B) Number of documents deleted.
C) Total documents in the collection.
D) Number of errors encountered.
**Answer:** B) Number of documents deleted.
**Explanation:** `deletedCount` reports the number of documents successfully removed.
---
**76. What happens if `deleteOne()` is called with a filter that matches multiple documents?**
A) Deletes all matching documents.
B) Deletes the first matching document.
C) Throws an error.
D) Deletes none.
**Answer:** B) Deletes the first matching document.
**Explanation:** `deleteOne()` removes the first document that matches the filter criteria.
---
**77. What happens if you run `deleteMany()` on an empty collection?**
A) All documents are deleted.
B) No documents are deleted, and no error occurs.
C) An error is thrown.
D) MongoDB shuts down the operation.
**Answer:** B) No documents are deleted, and no error occurs.
**Explanation:** MongoDB does not throw errors for `deleteMany()` on empty collections.
---
**78. Which operator helps to delete documents matching an array element?**
A) `$arrayElemMatch`
B) `$in`
C) `$all`
D) `$match`
**Answer:** A) `$arrayElemMatch`
**Explanation:** `$arrayElemMatch` matches documents containing an array element that meets the specified criteria.
---
### **Sharded Clusters**
**79. What is required to delete documents in a sharded collection?**
A) A filter matching the shard key.
B) Admin privileges.
C) No special requirements.
D) The `_id` field.
**Answer:** A) A filter matching the shard key.
**Explanation:** MongoDB requires shard key inclusion for operations on sharded collections.
---
### **Bulk Write and Atomicity**
**80. Can `deleteMany()` be part of a bulk write operation?**
A) Yes, combined with insert and update.
B) No, delete operations must be standalone.
C) Yes, but only with `deleteOne()`.
D) No, bulk write supports insert operations only.
**Answer:** A) Yes, combined with insert and update.
**Explanation:** MongoDB supports bulk write operations combining multiple CRUD methods.
---
### **Query Customization**
**81. How do you delete documents where a field value starts with a specific prefix?**
A) `$regex`
B) `$prefix`
C) `$startsWith`
D) `$begin`
**Answer:** A) `$regex`
**Explanation:** The `$regex` operator matches string patterns.
---
**82. Can you use aggregation operators in delete filters?**
A) Yes, with `$expr`.
B) No, aggregation is separate.
C) Yes, but only `$group` is supported.
D) No, aggregation operators throw errors in delete filters.
**Answer:** A) Yes, with `$expr`.
**Explanation:** The `$expr` operator allows expressions in query filters.
---
**83. What is the behavior of `deleteMany()` on documents with a TTL (Time to Live) index?**
A) TTL index automatically deletes documents.
B) `deleteMany()` ignores TTL-indexed documents.
C) TTL index disables `deleteMany()`.
D) Manual deletion is required.
**Answer:** A) TTL index automatically deletes documents.
**Explanation:** TTL indexes automate the deletion of expired documents.
---
Would you like further expansion, or does this complete your set?
4o
You said:
yes
ChatGPT said:
ChatGPT
Here is the final set of MCQs 84–100 to complete the collection:
Query and Index Interaction
84. How does the presence of an index affect the performance of delete operations?
A) Slows down delete operations.
B) Speeds up matching documents for deletion.
C) Prevents delete operations.
D) Has no effect on delete performance.
Answer: B) Speeds up matching documents for deletion.
Explanation: Indexes improve query performance, including delete operations, by quickly identifying matching documents.
85. Which type of index ensures that no two documents with the same value for a field can exist, thereby impacting deletions?
A) Text index.
B) Sparse index.
C) Unique index.
D) Compound index.
Answer: C) Unique index.
Explanation: A unique index enforces field uniqueness and might prevent inserts if deletions do not remove duplicates.
Best Practices and Optimization
86. What is a best practice to ensure efficient delete operations in large collections?
A) Use $regex in every query.
B) Always drop the entire collection.
C) Use indexed fields in the delete filter.
D) Avoid using filters altogether.
Answer: C) Use indexed fields in the delete filter.
Explanation: Indexed fields allow MongoDB to locate and delete documents more efficiently.
87. Why is it recommended to run find() with the same filter before executing a delete operation?
A) To preview which documents will be deleted.
B) To avoid errors.
C) It is mandatory for deletion.
D) MongoDB does not support direct deletion.
Answer: A) To preview which documents will be deleted.
Explanation: Running find() first ensures you only delete intended documents.
Security and Access Control
88. What permission is required to perform delete operations in MongoDB?
A) Read access.
B) Write access.
C) Read/Write access.
D) Admin access.
Answer: C) Read/Write access.
Explanation: Delete operations modify the database, requiring readWrite privileges.
89. What is the potential risk of running deleteMany() in production without specifying a filter?
A) All documents may be deleted accidentally.
B) The operation will fail.
C) It only deletes one document.
D) MongoDB prevents such operations by default.
Answer: A) All documents may be deleted accidentally.
Explanation: An empty filter matches all documents, which can lead to unintended data loss.
Advanced Use Cases
90. How can you delete documents based on a calculated value?
A) Use $expr in the filter.
B) Use $calc in the filter.
C) Delete operations do not support calculations.
D) Use $eval for calculations.
Answer: A) Use $expr in the filter.
Explanation: $expr enables query expressions that use aggregation operators.
91. What is the recommended way to delete documents that exceed a specific size limit?
A) Use $size directly in delete filters.
B) Use an aggregation pipeline with $expr.
C) MongoDB does not support size-based deletes.
D) Use a manual script.
Answer: B) Use an aggregation pipeline with $expr.
Explanation: Aggregation expressions can calculate document size, which can be used in the filter.
92. Which of the following is a valid way to delete documents with embedded documents matching a condition?
A) { "field.subfield": value }
B) { "field->subfield": value }
C) { "field.subfield": { $elemMatch: value } }
D) { "field.subfield": { $arrayElemMatch: value } }
Answer: A) { "field.subfield": value }
Explanation: Dot notation is used to access fields within embedded documents.
Specialized Index Handling
93. What happens if a delete operation matches a document that is part of a unique index?
A) The document is deleted normally.
B) The operation fails.
C) The unique index is dropped.
D) It deletes the document and rebuilds the index.
Answer: A) The document is deleted normally.
Explanation: The unique index remains intact after the document is removed.
94. How can you prevent accidental deletion of all documents in a collection?
A) Use MongoDB's built-in safeguard for empty filters.
B) Always include a specific filter in the delete operation.
C) Lock the database during delete operations.
D) Enable deletion constraints in the configuration file.
Answer: B) Always include a specific filter in the delete operation.
Explanation: Including filters ensures targeted deletions, avoiding unintended mass deletions.
Concurrency and Consistency
95. What happens if two clients attempt to delete the same document concurrently?
A) Both operations succeed.
B) One succeeds and the other fails.
C) Both fail.
D) The database crashes.
Answer: B) One succeeds and the other fails.
Explanation: MongoDB ensures atomicity, allowing only one operation to modify a document at a time.
96. What happens to indexes when a document is deleted?
A) Indexes are automatically updated.
B) Indexes are dropped and recreated.
C) Indexes must be manually updated.
D) The delete operation fails if indexes exist.
Answer: A) Indexes are automatically updated.
Explanation: MongoDB maintains index consistency automatically.
Transactional Behavior
97. Can delete operations be rolled back in a transaction?
A) Yes, if part of an active transaction.
B) No, delete operations are always permanent.
C) Only with replica sets.
D) Only with sharded clusters.
Answer: A) Yes, if part of an active transaction.
Explanation: Transactions in MongoDB allow rollback of changes, including deletes.
98. What happens if a delete operation is interrupted?
A) It completes partially.
B) It is rolled back.
C) It completes fully.
D) It leaves the database in an inconsistent state.
Answer: B) It is rolled back.
Explanation: MongoDB ensures atomicity, so incomplete operations are rolled back.
Miscellaneous
99. Can you delete a capped collection's documents?
A) Yes, using deleteOne().
B) No, capped collections do not support deletion.
C) Only with deleteMany().
D) Only if the _id field is indexed.
Answer: B) No, capped collections do not support deletion.
Explanation: Documents in capped collections cannot be deleted individually.
100. What MongoDB feature can be used to automate periodic deletions of expired documents?
A) TTL index.
B) Capped collections.
C) Background deletion.
D) Scheduled tasks.
Answer: A) TTL index.
Explanation: TTL indexes allow automatic deletion of documents after a specified expiration period.
