Python MongoDB Delete Document
Python provides two useful methods to delete documents in a collection.
The delete_one()
method is used to delete the first occurrence of the document (It is has more than one document in the result).
The delete_many()
method is used to delete many documents in the result.
Both methods takes one arguments, which is:
- Query Object :- A query objective define which document to delete
We will take a sample collection called "emp" from "mydatabase" and it contains four columns ("id", "name", "city", and "salary") and five documents.
{'_id': 2, 'name': 'bb', 'city': 'berlin', 'salary': 3500}
{'_id': 3, 'name': 'cc', 'city': 'new york', 'salary': 7000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 5, 'name': 'ee', 'city': 'berlin', 'salary': 1000}
Delete One Document - The delete_one() Method
We utilise the delete_one()
method to remove a document.
Note : Only the first occurrence is erased when the query discovers more than one document.
Example :- Delete the "berlin" city of the document :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
myquery = { "city": "berlin" }
mycol.delete_one(myquery)
for x in mycol.find():
print(x)
Output :-
{'_id': 3, 'name': 'cc', 'city': 'new york', 'salary': 7000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 5, 'name': 'ee', 'city': 'berlin', 'salary': 1000}
Note: There are three documents are selected by our query. But it deleted only the first document.
Delete Many Documents - The delete_many() Method
Use the delete_many()
function to remove more than one document.
Example :- Delete all documents where city="berlin" and salary < 6500 :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
myquery = {"city": "berlin", "salary": {"$lt" : 6500} }
cnt = mycol.delete_many(myquery)
print(cnt.deleted_count, "documents deleted")
for x in mycol.find():
print(x)
Output :-
{'_id': 3, 'name': 'cc', 'city': 'new york', 'salary': 7000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
Related Links
Delete All Documents in a Collection
Pass empty query objects on the delete_many()
method to remove all documents in a collection :
Example :- Remove all documents in the collection "emp" :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
x = mycol.delete_many({})
print(x.deleted_count, "documents deleted")
Output :-
Related Links