Deleting data in MongoDB can have serious consequences. Which of the following best explains why delete operations need care?
Think about what happens to data after you delete it and if MongoDB saves it automatically.
When you delete data in MongoDB, it is permanently removed unless you have backups. MongoDB does not keep deleted data by default, so you must be careful.
Consider a collection users with 5 documents. You run the command db.users.deleteMany({age: {$lt: 30}}). What will be the count of documents remaining if 3 users are younger than 30?
db.users.deleteMany({age: {$lt: 30}})
db.users.countDocuments()Think about how many documents are deleted and how many remain.
If 3 documents match the filter and are deleted, 5 - 3 = 2 documents remain.
Choose the correct MongoDB command to delete exactly one document where status is inactive.
Look for the official method that deletes a single document.
deleteOne() deletes a single matching document. deleteMany() deletes all matches. remove() is deprecated. delete() is not a valid method.
You need to delete millions of documents matching a condition in a large MongoDB collection. Which approach is best to avoid performance issues?
Think about how to reduce load on the database during large deletes.
Deleting in batches reduces lock time and resource usage, improving performance and avoiding timeouts.
You run db.orders.deleteMany({status: 'pending' || 'processing'}) expecting to delete documents with status 'pending' or 'processing'. Instead, it deletes only documents with status 'pending'. Why?
db.orders.deleteMany({status: 'pending' || 'processing'})Consider how JavaScript evaluates the expression inside the query object.
In JavaScript (MongoDB shell), 'pending' || 'processing' evaluates to 'pending' (first truthy value), so the query becomes {status: 'pending'}. Use {status: {$in: ['pending', 'processing']}} to match either.