DEV Community

Cover image for Seamless Integration: Building Python Applications with MongoDB
ajitdhulam for Python Discipline @EPAM India

Posted on

Seamless Integration: Building Python Applications with MongoDB

Seamless Integration: Building Python Applications with MongoDB

Building applications that interact with MongoDB using Python is a seamless process thanks to libraries like PyMongo. Python's versatility and MongoDB's flexibility complement each other, allowing you to create dynamic and data-driven applications.

1. Creating Python Applications with MongoDB:
Python applications can easily interact with MongoDB databases to perform a variety of tasks, from storing and retrieving data to performing complex data analysis. This integration is facilitated by PyMongo's intuitive API.

from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient()
db = client['mydatabase']
collection = db['mycollection']

# Insert a document
new_doc = {"name": "Ajit", "age": 28}
collection.insert_one(new_doc) 

# Query documents
result = collection.find({"age": {"$gt": 25}}) 

for doc in result:
    print(doc)
Enter fullscreen mode Exit fullscreen mode

2. Utilising Python Classes for Modelling:
Python's object-oriented capabilities can be leveraged to model MongoDB documents as Python classes, providing a structured and intuitive way to interact with data.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


    def save_to_db(self):
        collection.insert_one({"name": self.name, "age": self.age})



# Create and save a Person object
alice = Person("Ajit", 28)
alice.save_to_db()


# Query and display Person objects
result = collection.find({"age": {"$gt": 25}})


for doc in result:
    person = Person(doc["name"], doc["age"])
    print(person.name, person.age)
Enter fullscreen mode Exit fullscreen mode

By creating Python classes that mirror your MongoDB document structure, you can encapsulate data and operations, making your code more organized and maintainable.

Top comments (0)