MongoDB Delete One Document
MongoDB Delete One Document
In MongoDB, the deleteOne
operation is used to remove a single document from a collection that matches a specified filter. This method is essential for managing and maintaining data integrity within MongoDB collections.
Syntax
db.collection.deleteOne(filter, options)
The deleteOne
method takes a filter
to specify which document to remove and an optional options
parameter to customize the deletion.
Example MongoDB Delete One Document
Let's look at an example of how to use the deleteOne
method in the programGuru
collection in MongoDB:
1. Delete a Single Document
db.programGuru.deleteOne({ name: "John Doe" })
This command deletes a single document where the name
is John Doe
in the programGuru
collection.
Full Example
Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and deleting a single document.
Step 1: Switch to a Database
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
Step 2: Create a Collection
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
Step 3: Insert Documents into the Collection
This step involves inserting documents into the programGuru
collection.
db.programGuru.insertMany([
{ name: "John Doe", age: 30, email: "john.doe@example.com" },
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
We insert multiple documents into the programGuru
collection.
Step 4: Delete a Single Document from the Collection
This step involves using the deleteOne
method to remove a document from the programGuru
collection.
db.programGuru.deleteOne({ name: "John Doe" })
We delete a single document where the name
is John Doe
.
Conclusion
The MongoDB deleteOne
operation is crucial for managing data within collections. Understanding how to use this method allows you to efficiently remove specific documents, ensuring data integrity and proper management in MongoDB collections.