MongoDB db.collection.deleteone() (original) (raw)

Last Updated : 28 Feb, 2025

The **MongoDB deleteOne() method is an essential tool for removing a single document from a collection that matches a specified filter. It is widely used for precise deletion tasks, ensuring that we can manage your MongoDB collections effectively by removing specific documents based on certain criteria

In this article, We will learn about the **MongoDB deleteone() method in detail, covering its syntax, usage examples, and best practices.

What is the MongoDB deleteone() Method?

The deleteOne() method in **MongoDB is used to remove a single **document from a collection that matches a specified filter. This method is particularly useful when we want to delete one specific document based on certain criteria. Using deleteOne() effectively allows us to manage our MongoDB collections by removing specific documents based on our criteria, maintaining the **integrity and **relevance of our data.

**Key Features of deleteOne() Method:

**Syntax

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

**Parameter

**Optional Parameters

**Return

This method returns a document that contains the following fields:

**Examples of MongoDB deleteOne() Method

Let’s look at some examples of the deleteOne method in MongoDB. In the following examples, we are working with:

demo mongodb database and collection

Example 1: Delete One Document that Match Selection Criteria

Delete the first matched document whose age is 17 from the student collection using the deleteOne() method.

**Query:

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

original database and collection

**Output:

database and collection after deleteone method

**Explanation: The document with age: 17 is removed from the collection. If no document matches, **no document is deleted.

Example 2: Deleting a Document from the ‘student’ Collection Based on Age

Delete the first matched document whose age is less than 18 from the student collection using the deleteOne() method.

**Query:

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

before deletion

**Output:

after deletion

**Explanation: The $lt operator is used to specify that we want to delete the first document where age is less than 18. This query ensures that only one document is deleted, even if multiple documents meet the condition.

Conclusion

The **MongoDB deleteOne() method is a powerful and precise way to remove a single document from your collections. It is particularly useful when you need to delete **specific documents based on clear criteria while maintaining data integrity and performance. By understanding the syntax, optional parameters, and best practices, we can leverage this method to effectively manage our MongoDB data. This method is essential for keeping your MongoDB collections clean and relevant, ensuring optimal database performance.