Python MongoDB Delete Data
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 article is as follows (click on the image to view a larger version):
The following example deletes the document where the name
field is "Taobao":
Example
#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["tutorialprodb"]
mycol = mydb["sites"]
myquery = { "name": "Taobao" }
mycol.delete_one(myquery)
# Output after deletion
for x in mycol.find():
print(x)
The output is:
Deleting 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
#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["tutorialprodb"]
mycol = mydb["sites"]
myquery = { "name": {"$regex": "^F"} }
x = mycol.delete_many(myquery)
print(x.deleted_count, "documents deleted")
The output is:
1 documents deleted
Deleting 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
#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["tutorialprodb"]
mycol = mydb["sites"]
x = mycol.delete_many({})
print(x.deleted_count, "documents deleted")
The output is:
5 documents deleted
Deleting a Collection
We can use the drop()
method to delete a collection.
The following example deletes the "customers" collection:
Example
#!/usr/bin/python3
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["tutorialprodb"]
mycol = mydb["sites"]
mycol.drop()
The drop()
method returns true if the deletion is successful, and false if the collection does not exist.
We can check if the collection has been deleted using the following commands in the terminal:
> use tutorialprodb
switched to db tutorialprodb
> show tables;