In Python, To delete documents in MongoDB we can use the "pymongo" library.
We can use the "delete_one()" method to delete a single document or the "delete_many()" method to delete multiple documents that match a specific filter.
Here's how we can do it:
After importing "pymongo", we must provide a connection URL and database name to MongoClient.
# import pymongo library import pymongo # Connection URL and database name uri = "mongodb://localhost:27017/" database_name = "your_database_name" collection_name = "your_collection_name" # Connect to MongoDB server client = pymongo.MongoClient(uri) # Access the database db = client[database_name] # Access the collection collection = db[collection_name]
Make sure to replace "your_database_name" and "your_collection_name" with your actual database and collection name.
# Delete a single document filter = {"_id": ObjectId("document_id_to_delete")} result = collection.delete_one(filter) # Optionally, print result information # result.deleted_count will be 1, if query criteria match print("Deleted count:", result.deleted_count)
For deleting a single document, we can use "delete_one()" method and provide a filter specifying the document to delete.
"result.deleted_count" returns the number of documents deleted by the operation.
# Delete multiple documents filter = {"field_to_match": "value_to_match"} result = collection.delete_many(filter) # Optionally, print result information # result.deleted_count will be equal to no of documents match the query criteria. print("Deleted count:", result.deleted_count)
For deleting multiple documents, we can use "delete_many()" method and provide a filter specifying the documents to delete.
"result.deleted_count" returns the number of documents deleted by the operation.
Make sure to replace "field_to_match", and "value_to_match" with your actual filter criteria.
# Delete all documents from collection filter = {} # This query will remove all document from Collection result = collection.delete_many(filter) # result.deleted_count will be equal to no of documents match the query criteria. print("Deleted count:", result.deleted_count)
The above filter query will delete all documents from the collection, filter = {} indicates no selection criteria apply to delete documents, so all documents in the collection are eligible for deletion.
"result.deleted_count" returns the number of documents deleted by the operation.