MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?
I've tried
db.users.remove(*)
Although it returns an error so how do I go about clearing all records?
The argument to remove()
is a filter document, so passing in an empty document means 'remove all':
db.user.remove({})
However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove()
call vs the drop()
call.
More details in the docs.
You can delete all the documents from a collection in MongoDB, you can use the following:
db.users.remove({})
Alternatively, you could use the following method as well:
db.users.deleteMany({})
Follow the following MongoDB documentation, for further details.
To remove all documents from a collection, pass an empty filter document
{}
to either thedb.collection.deleteMany()
or thedb.collection.remove()
method.
Here is the command to delete all the records of a collection in the MongoDB shell or MongoDB Compass shell (_MongoSH).
show dbs -> to list all the database
use test-database -> to select the database
db.getCollection('orders').deleteMany({}) -> to select the collection and deletes all the data.
Or
show dbs -> to list all the database
use test-database -> to select the database
db.orders.remove({}) -> to select the collection and deletes all the data.
db.users.count()
db.users.remove({})
db.users.count()