Delete Document in MongoDB

The remove () method in MongoDB is used to delete the Document from Collection. The remove () method takes two parameters. The first parameter of the deletion criteria determines the Document to delete, and the second parameter is justOne.

Remove () method in MongoDB

The remove () method in MongoDB is used to delete the Document from Collection. The remove () method takes two parameters. The first parameter of the deletion criteria determines the Document to delete, and the second parameter is justOne.

  1. deletion criteria : (Optional) Specify the Document to delete.
  2. justOne : (Optional) If set to true or 1, only delete a Document.

Syntax

The basic syntax of remove () method is as follows:

 > db . COLLECTION_NAME . remove ( DELLETION_CRITTERIA ) 

For example

You monitor the Collection named mycol with the following data:

 { "_id" : ObjectId ( 5983548781331adf45ec5 ), "title" : "MongoDB Overview" } { "_id" : ObjectId ( 5983548781331adf45ec6 ), "title" : "NoSQL Overview" } { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title" : "Tutorials Point Overview" } 

The following example will delete all documents whose title is 'MongoDB Overview':

 > db . mycol . remove ({ 'title' : 'MongoDB Overview' }) > db . mycol . find () { "_id" : ObjectId ( 5983548781331adf45ec6 ), "title" : "NoSQL Overview" } { "_id" : ObjectId ( 5983548781331adf45ec7 ), "title" : "Tutorials Point Overview" } > 

Only delete a Document in MongoDB

If there are multiple records and you only want to delete the first record, set the justOne parameter in the remove () method.

 > db . COLLECTION_NAME . remove ( DELETION_CRITERIA , 1 ) 

Delete all Documents in MongoDB

If you do not specify the deletion criteria, MongoDB will delete all documents from Collection.This is equivalent to the truncate command in SQL .

 > db . mycol . remove () > db . mycol . find () > 

According to Tutorialspoint

Previous article: Update Document in MongoDB

Next article: Projection in MongoDB

4 ★ | 1 Vote