Python Mongodb Delete Document
# Python3.x Python MongoDB Delete Data
[ Python MongoDB](#)
We can use the `delete_one()` method to delete a single document. The first parameter of this method is a query object that specifies which data to delete.
**The test data used in this tutorial is as follows (click the image to view a larger version):*](#)
The following example deletes the document where the `name` field value is "Taobao":
## Example
```python
#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient
mycol = mydb
myquery = { "name": "Taobao" }
mycol.delete_one(myquery)
# Print the list after deletion
for x in mycol.find():
print(x)
The output result is:
!(#)
### Delete Multiple Documents
We can use the `delete_many()` method to delete multiple documents. The first parameter of this method is a query object that specifies which data to delete.
Delete all documents where the `name` field starts with "F":
## Example
```python
#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient
mycol = mydb
myquery = { "name": {"$regex": "^F"} }
x = mycol.delete_many(myquery)
print(x.deleted_count, "documents deleted")
The output result is:
1 documents deleted
### Delete All Documents in a Collection
If an empty query object is passed to the `delete_many()` method, it will delete all documents in the collection:
## Example
```python
#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient
mycol = mydb
x = mycol.delete_many({})
print(x.deleted_count, "documents deleted")
The output result is:
5 documents deleted
* * *
## Drop Collection
We can use the `drop()` method to delete an entire collection.
The following example deletes the `customers` collection:
## Example
```python
#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient
mycol = mydb
mycol.drop()
If the drop is successful, `drop()` returns `true`. If the drop fails (the collection does not exist), it returns `false`.
We can use the following command in the terminal to check if the collection has been deleted:
> use tutorialdb
switched to db tutorialdb
> show tables;
[ Python MongoDB](#)
YouTip