Delete Document - MongoDB


remove() method used to remove the document from the collection, and this method accepts two parameters. One is deletion criteria and second is justOne flag

  • Deletion Criteria are deletion criteria it is optional and according to documents will be removed.
  • JustOne is also optional if set to true or 1, then remove only one document.
SYNTAX:
Below is given basic syntax of remove() method:


>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)


EXAMPLE:  Point out the testCol collection has the following data.


{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"MongoDB Query overview by codefari "}


The below-given an example will remove all the documents whose title is ' MongoDB Query overview by codefari '


>db.testCol.remove({'title':'MongoDB Overview'})
>db.testCol.find()
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"MongoDB Query overview by codefari "}

Remove only one
If we want to remove the only first record from the document and there are multiple records then we will set JustOne parameter in remove() method.


>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All documents
If we don't define clearly deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent to SQL's truncate command.


>db.testCol.remove()
>db.testCol.find()

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...