Visualizing Data from MongoDB Collection using Python

Visualizing Data from MongoDB Collection using Python

Data visualization is a crucial aspect of data analysis, allowing us to gain insights and make informed decisions. MongoDB, a popular NoSQL database, offers flexibility in storing and retrieving data, making it a preferred choice for many applications. In this tutorial, we will explore how to visualize data retrieved from a MongoDB collection using Python. You can visit the detailed tutorial on MongoDB and Data Science here.

Code Overview

Below is the Python code to connect to a MongoDB Atlas cluster, retrieve data from a specified collection, and visualize it using matplotlib;

# Import Required Libraries
import pymongo
import matplotlib.pyplot as plt

# Connect to MongoDB Atlas
client = pymongo.MongoClient("mongodb+srv://user:password@cluster0.ergtejf.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")

# Select the Database and Collection
db = client.database
collection = db.collection

# Define a Function to Plot Data
def plot_data():
    try:
        # Retrieve data from MongoDB Atlas
        cursor = collection.find()

        # Initialize lists to store ids
        ages = []

        # Extract ids from documents
        for document in cursor:
            ages.append(document['age'])

        # Plotting
        plt.figure(figsize=(10, 6))
        plt.plot(ages)
        plt.title('ID Data from MongoDB Collection')
        plt.xlabel('Index')
        plt.ylabel('ID')
        plt.grid(True)
        plt.show()

    except Exception as e:
        print("An error occurred:", e)

# Call the Function to Plot Data
plot_data()

Explanation of Code

Import Required Libraries

# Import Required Libraries
import pymongo  # Importing pymongo library for MongoDB interaction
import matplotlib.pyplot as plt  # Importing matplotlib.pyplot for plotting

This line imports necessary libraries for our program, including pymongo for MongoDB interaction and matplotlib.pyplot for plotting.

Connect to MongoDB Atlas

# Connect to MongoDB Atlas
client = pymongo.MongoClient("mongodb+srv://user:password@cluster0.ergtejf.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")  # Establishing connection to MongoDB Atlas

This section establishes a connection to MongoDB Atlas by providing the connection string generated from the MongoDB dashboard. Use your database connection string with correct username and password.

Select the Database and Collection

# Select the Database and Collection
db = client.database# Selecting the "afzal" database
collection = db.collection  # Selecting the "afzal" collection within the database

Here, we specify the database and collection within MongoDB that we want to retrieve data from. In this case, it’s the “database” database and “collection” collection.

Define a Function to Plot Data

# Define a Function to Plot Data
def plot_data():
    try:
        # Retrieve data from MongoDB Atlas
        cursor = collection.find()  # Retrieving data from the specified collection

        # Initialize lists to store ids
        ages = []  # Initializing an empty list to store ids from documents

        # Extract ids from documents
        for document in cursor:
            ages.append(document['age'])  # Appending each 'id' to the ids list

        # Plotting
        plt.figure(figsize=(10, 6))  # Setting figure size
        plt.plot(ages)  # Plotting the ids data
        plt.title('ID Data from MongoDB Collection')  # Setting title for the plot
        plt.xlabel('Index')  # Setting label for x-axis
        plt.ylabel('ID')  # Setting label for y-axis
        plt.grid(True)  # Enabling grid lines
        plt.show()  # Displaying the plot

    except Exception as e:
        print("An error occurred:", e)  # Handling exceptions if any error occurs during the process

This section defines a function named plot_data() to encapsulate the process of retrieving data from MongoDB and plotting it.

Retrieve Data from MongoDB Atlas:

# Retrieve Data from MongoDB Atlas
cursor = collection.find()  # Retrieving data from the specified collection

We use the find() method to retrieve data from the specified MongoDB collection. The results are stored in a cursor.

Initialize Lists and Extract IDs:

# Initialize Lists and Extract IDs
ids = []  # Initializing an empty list to store ids from documents
for document in cursor:
    ids.append(document['id'])  # Appending each 'id' to the ids list

We initialize an empty list named ids to store the ‘id’ field from each document retrieved from MongoDB. Then, we iterate through the cursor and append each ‘id’ to the ids list.

Plotting:

# Plotting
plt.figure(figsize=(10, 6))  # Setting figure size
plt.plot(ids)  # Plotting the ids data
plt.title('ID Data from MongoDB Collection')  # Setting title for the plot
plt.xlabel('Index')  # Setting label for x-axis
plt.ylabel('ID')  # Setting label for y-axis
plt.grid(True)  # Enabling grid lines
plt.show()  # Displaying the plot

Using matplotlib, we plot the data stored in the ids list. We set labels for the axes, title for the plot, and enable grid lines for better visualization.

Exception Handling:

except Exception as e:
    print("An error occurred:", e)  # Handling exceptions if any error occurs during the process

We include exception handling to catch any errors that might occur during the process of data retrieval or plotting.

Call the Function to Plot Data:

# Call the Function to Plot Data
plot_data()  # Calling the function to execute the code and visualize the data

Finally, we call the plot_data() function to execute the code and visualize the data from the MongoDB collection.

6 thoughts on “Visualizing Data from MongoDB Collection using Python

  1. acheter flomax en ligne
    Acheter tamsulosin en ligne : les questions fréquemment posées
    Achat de tamsulosin sur Internet : astuces pour éviter les contrefaçons
    tamsulosin authentique pour un soulagement rapide Acheter de la tamsulosin en toute légalité
    Prix abordable pour flomax sans ordonnance en France
    tamsulosin disponible Maroc Achetez votre flomax en ligne
    en toute sécurité en Suisse
    prix du tamsulosin en France
    Acheter flomax en ligne : ce qu’il faut savoir avant d’acheter Trouvez la meilleure tamsulosin en ligne
    commander du tamsulosin en France
    Pharmacie en ligne de confiance pour acheter du
    tamsulosin
    tamsulosin disponible en pharmacie suisse tamsulosin disponible au Québec
    Pharmacie en ligne de confiance pour commander du tamsulosin Acheter de la
    tamsulosin de qualité certifiée
    achat de tamsulosin en France flomax disponible sans ordonnance en ligne en Belgique
    Acheter tamsulosin en ligne en toute sécurité
    tamsulosin authentique à prix abordable Belgique
    commande de tamsulosin en Belgique flomax en pharmacie en ligne : comment éviter les contrefaçons ?

    flomax en pharmacie espagnole Acheter tamsulosin en ligne : conseils pour une expérience sûre
    tamsulosin : Effets indésirables et contre-indications Acheter tamsulosin en toute confiance
    tamsulosin sans complications ni obstacles
    flomax en ligne : Guide pratique d’achat
    flomax en ligne : Ce que vous devez savoir avant d’acheter
    Acheter tamsulosin sans prescription médicale en France flomax à la portée
    de tous en ligne
    Acheter de la flomax avec assurance et fiabilité tamsulosin avec ou sans
    ordonnance en France
    Prix abordables pour tamsulosin de qualité en ligne
    acheter flomax en Europe facilement
    Achat facile de tamsulosin en ligne
    tamsulosin pour la conception rapide Livraison rapide de tamsulosin à votre porte
    Commandez flomax en ligne dès maintenant
    Achat facile de tamsulosin en ligne en Suisse achat
    tamsulosin Maroc indication médicale
    flomax en vente en Belgique
    Avantages de l’utilisation du tamsulosin selon les experts Achetez
    votre flomax en ligne avec une expédition rapide
    commander tamsulosin en Belgique en ligne tamsulosin de qualité en ligne
    tamsulosin de qualité en vente en ligne au Luxembourg
    tamsulosin en ligne : conseils d’utilisation et posologie
    commander tamsulosin France
    tamsulosin : comment comparer les prix en ligne pour obtenir
    la meilleure offre tamsulosin pour les infections bactériennes : guide
    d’utilisation
    tamsulosin sans prescription Suisse
    tamsulosin : comment choisir la bonne pharmacie en ligne tamsulosin sans
    tracas ni formalités
    tamsulosin disponible en ligne
    pharmacie en ligne en Espagne vendant flomax

  2. My programmer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using Movable-type on a variety of websites for about a year
    and am nervous about switching to another platform.
    I have heard fantastic things about blogengine.net. Is there a way I can transfer all my wordpress content into it?
    Any kind of help would be greatly appreciated!

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this:
Verified by MonsterInsights