Skip to main content

MongoDB deleteOne

Introduction

In a database system, deleting data is just as important as adding or updating it. MongoDB provides several methods to remove documents from collections, and deleteOne() is specifically designed to delete a single document that matches certain criteria.

In this tutorial, you'll learn how to use the deleteOne() method effectively to remove individual documents from MongoDB collections. This is a fundamental operation that every MongoDB developer should understand.

What is deleteOne?

The deleteOne() method is used to remove a single document from a MongoDB collection that matches the specified filter criteria. If multiple documents match the criteria, only the first document (according to the natural order within MongoDB) will be deleted.

Basic Syntax

javascript
db.collection.deleteOne(filter, options)

Parameters

  • filter: A document specifying the selection criteria for deletion.
  • options (optional): A document that specifies additional options for the operation.

Return Value

The method returns a document containing:

  • deletedCount - the number of documents deleted (0 or 1)
  • acknowledged - confirmation that the operation was acknowledged by the server

Using deleteOne - Basic Examples

Let's explore the deleteOne() method with some examples to understand how it works in practice.

Example 1: Delete a Document by ID

javascript
// Assume we have a collection named "users"
db.users.deleteOne({ _id: ObjectId("60a23c3fc2f8d91a6b31a2df") })

Output:

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

Example 2: Delete a Document by a Specific Field

Imagine we have a collection of products, and we want to remove a discontinued product:

javascript
// First, let's see what's in our products collection
db.products.find()

Output:

javascript
[
{
_id: ObjectId("60a23c40c2f8d91a6b31a2e0"),
name: "Laptop",
price: 1200,
stock: 15
},
{
_id: ObjectId("60a23c45c2f8d91a6b31a2e1"),
name: "Old Phone Model",
price: 300,
stock: 0,
discontinued: true
},
{
_id: ObjectId("60a23c4ac2f8d91a6b31a2e2"),
name: "Tablet",
price: 500,
stock: 25
}
]

Now let's delete the discontinued product:

javascript
db.products.deleteOne({ discontinued: true })

Output:

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

After deletion, our collection would look like:

javascript
db.products.find()

Output:

javascript
[
{
_id: ObjectId("60a23c40c2f8d91a6b31a2e0"),
name: "Laptop",
price: 1200,
stock: 15
},
{
_id: ObjectId("60a23c4ac2f8d91a6b31a2e2"),
name: "Tablet",
price: 500,
stock: 25
}
]

deleteOne with Complex Query Conditions

Example 3: Using Comparison Operators

Let's delete a product that's below a certain price threshold:

javascript
db.products.deleteOne({ price: { $lt: 400 } })

This command deletes the first document where the price is less than 400.

Example 4: Using Logical Operators

We can combine multiple conditions with logical operators:

javascript
db.products.deleteOne({
$and: [
{ stock: { $eq: 0 } },
{ discontinued: { $ne: true } }
]
})

This would delete the first product that has zero stock and is not marked as discontinued.

How deleteOne Behaves with Multiple Matches

An important thing to understand about deleteOne() is that when multiple documents match the filter criteria, only the first one encountered will be deleted. The order in which documents are stored and accessed in MongoDB is implementation-specific, so you shouldn't rely on a particular document being deleted if your filter could match multiple documents.

Example 5: Multiple Matching Documents

javascript
// Let's add some test data
db.inventory.insertMany([
{ item: "journal", qty: 25, status: "A" },
{ item: "notebook", qty: 50, status: "A" },
{ item: "paper", qty: 100, status: "D" },
{ item: "planner", qty: 75, status: "D" }
])

// Now let's delete one document with status "A"
db.inventory.deleteOne({ status: "A" })

Output:

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

If we check our collection now:

javascript
db.inventory.find({ status: "A" })

Output:

javascript
[
{ _id: ObjectId("..."), item: "notebook", qty: 50, status: "A" }
]

As you can see, only one of the documents with status "A" was deleted (the "journal" document), while the "notebook" document remains.

deleteOne with Options

Example 6: Using writeConcern Option

The writeConcern option allows you to specify the level of acknowledgment requested from MongoDB for write operations.

javascript
db.users.deleteOne(
{ username: "temporary_user" },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)

This operation will be acknowledged only when the delete has been applied to the majority of the replica set members within 5 seconds.

Real-World Applications

Example 7: Removing a User from a System

Let's consider a user management system where we need to delete a user account:

javascript
// First check if the user exists
const user = db.users.findOne({ email: "[email protected]" })

if (user) {
// Delete the user
const result = db.users.deleteOne({ email: "[email protected]" })

// Clean up related data in other collections
if (result.deletedCount === 1) {
db.userPreferences.deleteMany({ userId: user._id })
db.sessions.deleteMany({ userId: user._id })
console.log("User and related data successfully deleted")
}
}

Example 8: Order Cancellation System

When a customer cancels an order in an e-commerce system:

javascript
// Find the order first to get its details
const order = db.orders.findOne({ orderId: "ORD-12345" })

if (order && order.status === "PENDING") {
// Delete the order
const result = db.orders.deleteOne({ orderId: "ORD-12345" })

if (result.deletedCount === 1) {
// Release inventory that was reserved for this order
order.items.forEach(item => {
db.inventory.updateOne(
{ productId: item.productId },
{ $inc: { reservedQuantity: -item.quantity } }
)
})

// Notify customer
db.notifications.insertOne({
userId: order.userId,
message: `Your order #${order.orderId} has been cancelled successfully.`,
timestamp: new Date()
})
}
}

Best Practices for Using deleteOne

  1. Always use specific filters: Try to target exactly one document, preferably by _id or another unique field.

  2. Check the result: Always check the deletedCount property to confirm your operation had the intended effect.

  3. Use transactions for complex operations: If your delete operation is part of a larger process that modifies multiple collections, consider using transactions.

  4. Consider deleteMany for bulk operations: If you need to delete multiple documents matching the same criteria, deleteMany() is more efficient.

  5. Be cautious with indexes: Ensure your query filter utilizes existing indexes for better performance, especially in large collections.

  6. Handle related data: When deleting a document, consider whether you also need to delete related data in other collections.

What deleteOne Cannot Do

  • It cannot delete more than one document in a single operation.
  • It cannot perform a "soft delete" (marking records as deleted without removing them) without you explicitly implementing that pattern.
  • It does not return the deleted document (use findOneAndDelete() for that).

Summary

The deleteOne() method in MongoDB is a straightforward yet powerful way to remove a single document from a collection. Key points to remember:

  • It deletes only the first document that matches the filter criteria
  • It returns information about the operation, including how many documents were deleted
  • When multiple documents match the filter, the choice of which document gets deleted is not determined by any specific order
  • For precise deletion, always use unique identifiers like _id

By understanding the behavior and proper usage of deleteOne(), you can efficiently manage your MongoDB data and implement clean removal operations in your applications.

Exercises

  1. Create a collection named "practice" and insert five documents with different name values. Then, write a query to delete one document with a specific name.

  2. Write a deleteOne() operation that uses the $or operator to delete a document that meets one of two conditions.

  3. Implement a function that safely deletes a document by its ID and handles the case when no document matches.

  4. Create a scenario where you need to delete a document and also update a related document in another collection. Implement this using proper error handling.

Additional Resources

Now that you understand how to use deleteOne(), you can effectively manage the removal of individual documents in your MongoDB applications!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)