How to Delete Data in MongoDB Using Python?

Estimated read time 2 min read

To delete data in MongoDB using Python, you can use the delete_one or delete_many methods provided by the PyMongo library. Here’s an example of how you can do it:

from pymongo import MongoClient

# Establish a connection to MongoDB
client = MongoClient('mongodb://localhost:27017')

# Access the database and collection
db = client['your_database_name']
collection = db['your_collection_name']

# Delete a single document
result = collection.delete_one({'_id': 'document_id'})
print(f"Deleted {result.deleted_count} document.")

# Delete multiple documents
result = collection.delete_many({'field': 'value'})
print(f"Deleted {result.deleted_count} documents.")

In the above code:

  1. First, you need to establish a connection to your MongoDB server using the MongoClient class. Make sure to provide the appropriate connection string.
  2. Next, you need to access the specific database and collection where your documents are stored.
  3. To delete a single document, you can use the delete_one method and pass a query that matches the document you want to delete. In the example, we use {'_id': 'document_id'} to specify the document with a specific _id value.
  4. The delete_one method returns a DeleteResult object, which contains information about the deletion. You can access the deleted_count attribute to get the number of documents deleted.
  5. To delete multiple documents, you can use the delete_many method and pass a query that matches the documents you want to delete. In the example, we use {'field': 'value'} to specify documents that have a specific field-value pair.
  6. Again, the delete_many method returns a DeleteResult object, and you can access the deleted_count attribute to get the number of documents deleted.

Make sure to replace 'your_database_name' and 'your_collection_name' with the actual names of your database and collection. Adjust the deletion queries ({'_id': 'document_id'} and {'field': 'value'}) to match your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply