MongoDB – Delete Document

MongoDB Delete method is an essential method, used to delete or remove a collection or a document existing in a MongoDB Collection. Upon creating a document or updating an existing document, we might encounter a situation where we might have to delete some records, which is where the Delete method can be implemented. MongoDB’s Delete methods are shell commands, which allow a user to delete or remove the records or documents upon insertion and if not needed. Multiple programming languages support these methods to delete records with APIs.

Syntax:

There are two basic ways to implement Delete Method, which are deleteOne method and deleteMany method. Every method has its functions and applicability, based on which it can be used.

1. Syntax for deleteOne method

db.collection.deleteOne( < filter > )

2. Syntax for deleteMany method

db.collection.deleteMany( < filter > )

Output:

MongoDB Delete 1

As you can see in the above help, both methods take optional parameters. Followed by the working of the method, respectively.

The syntax for Delete without filter or parameters:

We have seen delete document, with single or multiple documents and how to add filters to make sure specific documents are deleted. If we want to delete every single document inside a collection, we will pass simply empty filter, which is, {}.

db.locs.deleteMany( {} )

How does Delete Command work in MongoDB?

  • Specifically, the deleteOne method will delete the very first document, which matches with the mentioned filter. Using the field with a unique index like “_id” could work in a better way for precious deletion.
  • With the Delete Command working, there is an execution, which occurs only in case of capped collections, which are collections with fixed size and will overwrite its oldest records when it reaches a maximum set limit. To remove such capped collections and proceed with normal working, it is recommended to implement the db.collection.drop() method.
  • Working on the remove method is similar to delete(), but it differs only with the return values. When deleted with the delete method, the return will be the acknowledgement of the deletion and number of records deleted, while with remove method, write result is returned with several records removed.

Examples of MongoDB Delete

Given below are the examples mentioned:

Example #1 – deleteOne

Code:

db.code.deleteOne({"name":"malti"})

Output:

MongoDB Delete 2

Example #2 – deleteMany

Code:

db.code.find()
db.code.deleteMany({"city":"Pune"})

Output:

deletemany

Example #3 – Complete Deletion

A delete method that deletes every single record available in the collection, at once. By simply not specifying any filter, we attempt to delete every single record stored in the collection.

Code:

db.locs.deleteMany( {} )
db.code.find().count()

Output:

complete deletion

Similar Posts

Leave a Reply

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