MongoDB deleteOne()

In MongoDB the db.collection.deleteOne() method removes a single document from a collection. In other words, it deletes it.

The collection part is the name of the collection with which to remove the document from.

Example

Let’s populate a collection called employees with five documents:

db.employees.insertMany([
    { _id: 1, name: "Sandy", salary: 55000 },
    { _id: 2, name: "Sarah", salary: 128000 },
    { _id: 3, name: "Fritz", salary: 25000 },
    { _id: 4, name: "Chris", salary: 45000 },
    { _id: 5, name: "Beck", salary: 82000 }
    ])

Let’s now use db.collection.deleteOne() to delete one of those documents.

db.employees.deleteOne({ "_id": 4 })

Result:

{ "acknowledged" : true, "deletedCount" : 1 }

This deleted employee number 4.

Let’s take a look at the collection to verify.

db.employees.find()

Result:

{ "_id" : 1, "name" : "Sandy", "salary" : 55000 }
{ "_id" : 2, "name" : "Sarah", "salary" : 128000 }
{ "_id" : 3, "name" : "Fritz", "salary" : 25000 }
{ "_id" : 5, "name" : "Beck", "salary" : 82000 }

We can see that employee number 4 no longer exists in the collection.

Using a Broader Condition

In the previous example, we used the _id field of the employee that we wanted to delete. Because the _id field is the unique identifier for each document, this allowed us to delete the exact document that we wanted to be deleted.

It’s also possible to delete a single document without being so precise about which one is deleted. For example, you can use a broad filter that returns many documents, but only delete the first document from those results.

For example, we could filter by employees that earn more than 80,000 per year, then delete the first document in that group.

db.employees.deleteOne({ "salary": { $gt: 80000 } })

Result:

{ "acknowledged" : true, "deletedCount" : 1 }

In this example, only one document was deleted, even though there were two documents that matched the criteria.

We can take a look at the collection to see which one was deleted.

db.employees.find()

Result:

{ "_id" : 1, "name" : "Sandy", "salary" : 55000 }
{ "_id" : 3, "name" : "Fritz", "salary" : 25000 }
{ "_id" : 5, "name" : "Beck", "salary" : 82000 }

We can even take it a step further and remove all filters, which means that the it chooses from all documents in the collection.

db.employees.deleteOne({})

Result:

{ "acknowledged" : true, "deletedCount" : 1 }

Once again we can check the collection to see which one was deleted.

db.employees.find()

Result:

{ "_id" : 3, "name" : "Fritz", "salary" : 25000 }
{ "_id" : 5, "name" : "Beck", "salary" : 82000 }

As expected, the first document was deleted.

More Information

The db.collection.deleteOne() method also accepts optional parameters such as collation, hint, and writeConcern.

See the MongoDB documentation for more information.