Categories
mongodb python

python with mongodb

In this post, we will see about connecting Python with MongoDB.

MongoDB is a fast and reliable NO SQL database that is used to store the data in JSON structure.

PyMongo

Here we are using the PyMongo library to connect MongoDB from python. refer https://pymongo.readthedocs.io/en/stable/

We already installed MongoDB, RoboMongo & pyhcarm for our development

I have created a database called avengers which have a collection as avengersdetails as like below image

PyMongo

Command to install pymongo library

pip install pymongo

PyMongo Import

import pymongo

In our example, we are using the OOPS concept to create the connection and fetch the data from Mongo DB.
Below line is the starting point of the code

if __name__ == "__main__":

Python with MongoDB Example

import pymongo


class MongoDbConn:

    # __init__ method will be used to initialize the variable
    # We need to pass the mongo db url & database name to this method
    def __init__(self, host_url, database):
        self.host_details = host_url
        self.db_name = database

    # Once you create the object you can connect the connection object from below method
    def get_mongodb_connection_details(self) -> object:
        my_client = pymongo.MongoClient(self.host_details)
        my_db = my_client[self.db_name]
        return my_db


if __name__ == "__main__":
    # Create an object for our class MongoDbConn
    obj = MongoDbConn("mongodb://localhost:27017/", "avengers")
    # Create database connection from the below line
    db_connection = obj.get_mongodb_connection_details()
    # pass your collection(table) name in below line
    collection_details = db_connection["avengersdetails"]
    for data in collection_details.find():
        print(data)

Output

{'_id': ObjectId('5fd0e603549a851a24a48c36'), 'ID': '1', 'Character Name': 'Hulk', 'Real Name': 'Mark Ruffalo'}
{'_id': ObjectId('5fd0e603549a851a24a48c37'), 'ID': '2', 'Character Name': 'Thor', 'Real Name': 'Chris Hemsworth'}
{'_id': ObjectId('5fd0e603549a851a24a48c38'), 'ID': '3', 'Character Name': 'Black Widow', 'Real Name': 'Scarlett Johansson'}
{'_id': ObjectId('5fd0e603549a851a24a48c39'), 'ID': '4', 'Character Name': 'Iron Man', 'Real Name': 'Robert Downey Jr'}
{'_id': ObjectId('5fd0e603549a851a24a48c3a'), 'ID': '5', 'Character Name': 'Captain America', 'Real Name': 'Chris Evans'}

Related Articles