Open In App

MongoDB – db.collection.deleteone()

The deleteOne() method in MongoDB deletes the first document from the collection that matches the given selection criteria. It will delete/remove a single document from the collection.

If you use this method in the capped collection, then this method will give a WriteError exception, so to delete documents from the capped collection use the drop() method.



If you use this method in the sharded collection, then the query expression passed in this method must contain the sharded key/_id field, if not then this method will give an error. You can also use this method in multi-document transactions.

Syntax

db.Collection_name.deleteOne(
selection_criteria:<document>,
{
    writeConcern: <document>,
    collation: <document>,
    hint: <document|string>
})



Parameter

Optional Parameters

Return

This method returns a document that contains the following fields:

MongoDB deleteOne Method Examples

Let’s look at some examples of the deleteOne method in MongoDB.

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Four documents contains the name and the age of the students

Delete One Document that Match Selection Criteria Example

Delete the first matched document whose age is 17:

db.student.deleteOne({age:17})

Here, we delete the first document that matches the filter query(i.e., age:17) from the student collection using the deleteOne() method.

After deletion:

Example 2

Delete the first matched document whose age is less than 18:

db.student.deleteOne({age:{$lt:18}})

Here, we delete the first document that matches the filter query(i.e., {age:{$lt:18}}) from the student collection using the deleteOne() method.

Note: $lt operator means less than.

After deletion:

Conclusion

The deleteOne method in MongoDB is used to delete a single document from a collection. The deleteOne method only deletes the document that matches the selection criteria.

We have explained the method with simple definitions and examples. The examples demonstrate different use cases of the db.Collection_name.deleteOne() method.

Article Tags :