📜  MongoDB – db.collection.deleteone()(1)

📅  最后修改于: 2023-12-03 14:44:21.939000             🧑  作者: Mango

MongoDB – db.collection.deleteOne()

Introduction

MongoDB is a document-based NoSQL database that provides a flexible and scalable solution for storing and querying data. One of the key operations in any database is the ability to delete data. In MongoDB, the db.collection.deleteOne() method is used to delete a single document that matches the specified criteria from a collection.

Syntax

The basic syntax for using the db.collection.deleteOne() method is as follows:

db.collection.deleteOne(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)

Here, <filter> is a document that specifies the criteria for selecting the document(s) to be deleted. The method will delete the first document in the collection that matches the filter.

Example

Let’s look at a simple example of how to use the db.collection.deleteOne() method:

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

This command will delete the first document in the users collection where the name field is equal to "John". If there are multiple documents that match the filter, only the first one will be deleted.

Options

In addition to the <filter> parameter, the db.collection.deleteOne() method also supports the following optional parameters:

  • writeConcern: Specifies the level of write concern for the operation.
  • collation: Specifies the collation to use for string comparisons during the operation.
Conclusion

In this tutorial, we’ve looked at how to use the db.collection.deleteOne() method in MongoDB to delete a single document from a collection. Whether you’re building a small application or a large-scale system, MongoDB provides a robust and flexible solution for storing and managing your data.