This article explains how to delete data from MongoDB using Python. You’ll learn how to delete documents from MongoDB collections using PyMongo operations such as delete_one() and delete_many().
MongoDB delete_one()
Use the delete_one() method to delete a single document from a collection in MongoDB. If multiple documents meet the specified condition, only the first document that is found is deleted. Below is the syntax:
collection.delete_one(filter)
The required parameter is a dictionary defining the condition for the delete statement. Consider the following example:
import pymongo #establishing connection to mongodb client = pymongo.MongoClient("mongodb://localhost:27017/") #getting the database db = client["mydatabase"] #getting the collection collection = db["customers"] #deleting a single document from the collection query = { "address": "Mountain 21" } result = collection.delete_one(query) print(result.deleted_count , " record deleted.")
The output will show the record count that was deleted.
MongoDB delete_many()
Use the delete_many() method to delete multiple documents from a collection in MongoDB. Below is the syntax:
collection.delete_many(filter)
The required parameter is a dictionary defining the condition for the delete statement. Consider the following example:
import pymongo #establishing connection to mongodb client = pymongo.MongoClient("mongodb://localhost:27017/") #getting the database db = client["mydatabase"] #getting the collection collection = db["customers"] #deleting multiple documents from the collection query = { "address": {"$regex": "^S"} } result = collection.delete_many(query) print(result.deleted_count, " records deleted.")
The output will show the number of records deleted from the collection based on the query.
Python delete_all_documents_in_a_collection
In case you want to delete all records in a collection, you can use the delete_many() method and pass an empty dictionary as filter. Consider the following example:
import pymongo #establishing connection to mongodb client = pymongo.MongoClient("mongodb://localhost:27017/") #getting the database db = client["mydatabase"] #getting the collection collection = db["customers"] #deleting all records from the collection query = {} result = collection.delete_many(query) print(result.deleted_count, " records deleted.")
The output will show the number of records deleted from the collection.
Conclusion:
To sum it up, we’ve learned how to delete data from MongoDB collections using Python. There are two PyMongo methods for deleting data from collections: delete_one() and delete_many(). The delete_one() method deletes a single document from a collection based on a criteria, while the delete_many() method deletes multiple documents based on criteria.