Jul 5, 2015

Delete Document - MongoDB

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

Deletion Criteria is 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 collectioin has following data.


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


Below given 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 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 of SQL's truncate command.


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