Introduction
Sometimes you want to remove all data from a collection to start fresh or clear old information.
Jump into concepts and practice - no test required
Sometimes you want to remove all data from a collection to start fresh or clear old information.
db.collection.deleteMany({})The empty curly braces {} mean 'match all documents'.
This command deletes all documents but keeps the collection itself.
users collection.db.users.deleteMany({})orders collection.db.orders.deleteMany({})This example inserts two products, deletes all products, then shows the empty collection.
use shopDB
db.products.insertMany([{name: 'Pen', price: 1}, {name: 'Notebook', price: 5}])
db.products.deleteMany({})
db.products.find().toArray()Deleting all documents does not delete the collection itself.
Use deleteMany({}) carefully because it removes everything.
Use deleteMany({}) to remove all documents from a collection.
The collection remains but is empty after deletion.
This is useful for clearing data without dropping the collection.
db.collection.deleteMany({}) do?deleteMany method removes documents matching the filter. An empty filter {} matches all documents.{} deletes all documents but does not remove the collection itself.users?deleteMany, which requires a filter argument.{} as the filter deletes all documents in the collection.products with 5 documents, what will be the result of running db.products.deleteMany({}) followed by db.products.find().toArray()?deleteMany({}) deletes all documents in the collection.find() returns no documents, so toArray() returns an empty array.db.orders.deleteMany() to delete all documents in the orders collection but get an error. What is the likely cause?deleteMany method requires a filter argument; omitting it causes a syntax error.{} as argument.logs collection but keep the collection and its indexes intact. Which command should you use?drop() removes the entire collection and indexes, while deleteMany({}) removes all documents but keeps collection and indexes.deleteMany({}) clears all documents without dropping the collection or indexes.