How to Create CRUD Operations with MongoDB and Python?

Estimated read time 2 min read

To create CRUD operations (Create, Read, Update, Delete) with MongoDB using Python, you can use the PyMongo library, which provides a Python API for MongoDB. Here’s an example that demonstrates the basic implementation of CRUD operations:

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']

# Create operation
def create_document(document):
    result = collection.insert_one(document)
    print(f"Document created with ID: {result.inserted_id}")

# Read operation
def read_documents():
    documents = collection.find()
    for document in documents:

# Update operation
def update_document(document_id, updated_data):
    result = collection.update_one({'_id': document_id}, {'$set': updated_data})
    if result.modified_count == 1:
        print("Document updated successfully.")
        print("Document not found.")

# Delete operation
def delete_document(document_id):
    result = collection.delete_one({'_id': document_id})
    if result.deleted_count == 1:
        print("Document deleted successfully.")
        print("Document not found.")

# Usage examples
document1 = {'name': 'John', 'age': 25, 'email': ''}

document2 = {'name': 'Jane', 'age': 30, 'email': ''}


updated_data = {'age': 26}
update_document(document1['_id'], updated_data)



In the above code:

  1. First, you establish a connection to your MongoDB server using the MongoClient class. Make sure to provide the appropriate connection string.
  2. Next, you access the specific database and collection where your documents are stored.
  3. The create_document function demonstrates the create operation by inserting a new document into the collection using insert_one. It returns the inserted ID.
  4. The read_documents function demonstrates the read operation by retrieving all documents from the collection using find. It iterates over the result and prints each document.
  5. The update_document function demonstrates the update operation by updating a specific document identified by its ID. It uses update_one with the $set operator to update the specified fields.
  6. The delete_document function demonstrates the delete operation by deleting a specific document identified by its ID using delete_one.
  7. Lastly, the usage examples show how to call these functions to perform the respective CRUD operations.

Make sure to replace 'your_database_name' and 'your_collection_name' with the actual names of your database and collection. Adjust the document structure and field names based on your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply