Remove and delete documents in MongoDB

Remove and delete documents in MongoDB

To delete a document we use the method "remove", "deleteOne" or "deleteMany".

Remove Method in MongoDB

MongoDB remove Syntax

db.collection.remove(
	query: <document>,
	justOne: <boolean>
)

Description of parameters

Parameter Type Default value Description
query document - <Optional> {} Specifies deletion criteria using query operators.
justOne boolean - <Optional> false If set to true, remove method will only delete one document unlike the false value which delete all documents matching the deletion criteria

Find more about query operators in the following link: [Query operators]

Delete examples

Remove all documents

If the deletion criteria is set to empty, the remove method will delete all the documents inside the specified collection

> db.test.remove({})

Remove using query deletion criteria

Delete all documents that have a field views and its value is greater than 20

> db.test.remove( { views: { $gt: 20 } } )

deleteOne and deleteMany Method in MongoDB

deleteOne and deleteMany have the same behavior as remove with option true and false, respectively

Example of deleteOne

> db.test.deleteOne( { _id: ObjectId("5e37dd95890d645061ea7dc6") } )

Example of deleteMany

> db.test.deleteMany( { views: { $gt: 20 } } )