Using the Mongo DB Shell to remove all elements in a collection

June 19, 2021

In my recent experiments with using MongoDB, I came across a need to remove all the records from a collection - the equivalent of DELETE FROM MYTABLE in SQL.

It turns out that, in order to do this, you need to use the Mongo DB Shell. This comes with Compass, although you may miss it, tucked away at the bottom:


By default it’s collapsed, but once you un-collapse it, you can do a number of things. The first thing you should do is tell it which DB you would like to use (for the purpose of this, let’s assume the database is called aardvark):

> use aardvark
< 'switched to db aardvark'

You can see which collections you have in the database, like this:

> db.getCollectionNames()
< [ 'collection1', 'collection2' ]

You can also see some information about a specific collection; for example:

> db.collection1.exists()

This should return a JSON document that details collection1.

In my case, I wanted to clear everything from the collection:

> db.collection1.deleteMany({ })

You can also pass this a specific filter, but this allows you to delete everything.


Profile picture

A blog about one man's journey through code… and some pictures of the Peak District

© Paul Michaels 2024