MongoDB query Remove/Delete records in a Collection

MongoDB query Delete records

Today in this article, we will cover how to write MongoDB query Remove/Delete records in a Collection. We will see a simple query to delete all the records and also delete records based on filter criteria.

We will use the Mongo Shell query to perform the deletes. If you are interested to perform delete within Atlas UI compass please refer to this article.

You may find the need to delete the records from a mongo collection from time to time, especially when performing the schema update or data cleanup.

While dropping the collection is another easier way to delete the records which not only deletes the collection but also deletes all the records along with indexes if any.

MongoDB Delete All records

But if you want to delete the records without deleting the collection or indexes then you can use the below command from the mongo shell

Switch to the Database

Switch to the Database using the command “use”

Command :

use <Your DB>

Example

MongoDB Delete all records MongoDB query RemoveDelete records in a Collection

Delete all records using deleteMany

We can easily delete all records using deleteMany() method

Command

db.<collection name>.deleteMany({})

Example

 db.employee1.deleteMany({}) 

MongoDB query Delete records

Delete records for filter criteria using deleteMany methods

Example 1:

db.employee1.deleteOne({Name:"Meery"})

Above query will delete the first matching records(Where Name fields match the value as “Merry” ) for the given filter condition

Example 2:

db.employee1.deleteMany({Name:"Meery"})

The above query will delete all matching records(one or multiple) for the given filter condition.

Delete all records using remove() methods

We can also easily delete all records using remove() method.

Command

db.<collection name>.remove({})

Example 1

db.employee1.remove({}) 

Delete records for filter criteria using remove() methods

Example

db.employee1.remove({Name:"John"})

Above query will remove records where Name fields match with value of “John”

Delete records using the Unset operator

One can also delete the records using unset operator too.

For more details please visit below,

References :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *