Introduction to MongoDB collection.deleteOne() Method

MongoDB is a non-relational database management system that provides multiple methods for deleting document data in a database, one of which is the deleteOne() method. This article will introduce the deleteOne() method in MongoDB, including its syntax, use cases, examples, and conclusions.

Syntax

The syntax of the deleteOne() method is as follows:

db.collection.deleteOne(filter, options)

Here, collection is the collection name, filter is a document that specifies the document to be deleted, and options is an optional parameter that specifies the options for the delete operation.

Use Cases

The deleteOne() method is mainly used to delete a single document in a collection. If you only want to delete one document in a collection, instead of all documents that match the criteria, you can use the deleteOne() method.

Examples

Here are two examples of using the deleteOne() method, one to delete a single document and one to delete the first document that matches the criteria.

Example 1: Delete a Single Document

Suppose we have a collection named “users” that stores multiple user information documents. Now, we want to delete the document for the user named “Tom”. We can use the following code:

db.users.deleteOne({ name: "Tom" })

After executing the above code, MongoDB will delete the document for the user named “Tom”.

Example 2: Delete the First Document That Matches the Criteria

Suppose we have a collection named “products” that stores multiple product information documents. Now, we want to delete the documents for products with a stock quantity less than or equal to 0. We can use the following code:

db.products.deleteOne({ stock: { $lte: 0 } })

After executing the above code, MongoDB will delete the first document that matches the criteria of having a stock quantity less than or equal to 0.

Conclusion

The deleteOne() method is a method provided by MongoDB for deleting a single document. It can be used to delete a document in a collection based on a specified condition, or to delete the first document that matches the condition. When using this method, it is important to pay attention to the use of parameters.