{"id":3008,"date":"2024-03-27T11:23:27","date_gmt":"2024-03-27T06:23:27","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=3008"},"modified":"2024-03-27T11:23:31","modified_gmt":"2024-03-27T06:23:31","slug":"visualizing-data-from-mongodb-collection-using-python","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2024\/03\/27\/visualizing-data-from-mongodb-collection-using-python\/","title":{"rendered":"Visualizing Data from MongoDB Collection using Python"},"content":{"rendered":"\n<p>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. <a href=\"https:\/\/afzalbadshah.com\/index.php\/category\/courses\/data-driven-applications-using-mongodb-python-and-google-colab\/\" target=\"_blank\" rel=\"noopener\" title=\"\">You can visit the detailed tutorial on MongoDB and Data Science here. <\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Code Overview<\/strong><\/h3>\n\n\n\n<p>Below is the Python code to connect to a MongoDB Atlas cluster, retrieve data from a specified collection, and visualize it using matplotlib;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Import Required Libraries\nimport pymongo\nimport matplotlib.pyplot as plt\n\n# Connect to MongoDB Atlas\nclient = pymongo.MongoClient(\"mongodb+srv:\/\/user:password@cluster0.ergtejf.mongodb.net\/?retryWrites=true&amp;w=majority&amp;appName=Cluster0\")\n\n# Select the Database and Collection\ndb = client.database\ncollection = db.collection\n\n# Define a Function to Plot Data\ndef plot_data():\n    try:\n        # Retrieve data from MongoDB Atlas\n        cursor = collection.find()\n\n        # Initialize lists to store ids\n        ages = &#91;]\n\n        # Extract ids from documents\n        for document in cursor:\n            ages.append(document&#91;'age'])\n\n        # Plotting\n        plt.figure(figsize=(10, 6))\n        plt.plot(ages)\n        plt.title('ID Data from MongoDB Collection')\n        plt.xlabel('Index')\n        plt.ylabel('ID')\n        plt.grid(True)\n        plt.show()\n\n    except Exception as e:\n        print(\"An error occurred:\", e)\n\n# Call the Function to Plot Data\nplot_data()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Explanation of Code<\/strong><\/h3>\n\n\n\n<p><strong>Import Required Libraries<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Import Required Libraries\nimport pymongo  # Importing pymongo library for MongoDB interaction\nimport matplotlib.pyplot as plt  # Importing matplotlib.pyplot for plotting<\/code><\/pre>\n\n\n\n<p>This line imports necessary libraries for our program, including <code>pymongo<\/code> for MongoDB interaction and <code>matplotlib.pyplot<\/code> for plotting.<\/p>\n\n\n\n<p><strong>Connect to MongoDB Atlas<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Connect to MongoDB Atlas\nclient = pymongo.MongoClient(\"mongodb+srv:\/\/user:password@cluster0.ergtejf.mongodb.net\/?retryWrites=true&amp;w=majority&amp;appName=Cluster0\")  # Establishing connection to MongoDB Atlas<\/code><\/pre>\n\n\n\n<p>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.<\/p>\n\n\n\n<p><strong>Select the Database and Collection<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Select the Database and Collection\ndb = client.database# Selecting the \"afzal\" database\ncollection = db.collection  # Selecting the \"afzal\" collection within the database<\/code><\/pre>\n\n\n\n<p>Here, we specify the database and collection within MongoDB that we want to retrieve data from. In this case, it&#8217;s the &#8220;database&#8221; database and &#8220;collection&#8221; collection.<\/p>\n\n\n\n<p><strong>Define a Function to Plot Data<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Define a Function to Plot Data\ndef plot_data():\n    try:\n        # Retrieve data from MongoDB Atlas\n        cursor = collection.find()  # Retrieving data from the specified collection\n\n        # Initialize lists to store ids\n        ages = &#91;]  # Initializing an empty list to store ids from documents\n\n        # Extract ids from documents\n        for document in cursor:\n            ages.append(document&#91;'age'])  # Appending each 'id' to the ids list\n\n        # Plotting\n        plt.figure(figsize=(10, 6))  # Setting figure size\n        plt.plot(ages)  # Plotting the ids data\n        plt.title('ID Data from MongoDB Collection')  # Setting title for the plot\n        plt.xlabel('Index')  # Setting label for x-axis\n        plt.ylabel('ID')  # Setting label for y-axis\n        plt.grid(True)  # Enabling grid lines\n        plt.show()  # Displaying the plot\n\n    except Exception as e:\n        print(\"An error occurred:\", e)  # Handling exceptions if any error occurs during the process<\/code><\/pre>\n\n\n\n<p>This section defines a function named <code>plot_data()<\/code> to encapsulate the process of retrieving data from MongoDB and plotting it.<\/p>\n\n\n\n<p><strong>Retrieve Data from MongoDB Atlas:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Retrieve Data from MongoDB Atlas\ncursor = collection.find()  # Retrieving data from the specified collection<\/code><\/pre>\n\n\n\n<p>We use the <code>find()<\/code> method to retrieve data from the specified MongoDB collection. The results are stored in a cursor.<\/p>\n\n\n\n<p><strong>Initialize Lists and Extract IDs:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Initialize Lists and Extract IDs\nids = &#91;]  # Initializing an empty list to store ids from documents\nfor document in cursor:\n    ids.append(document&#91;'id'])  # Appending each 'id' to the ids list<\/code><\/pre>\n\n\n\n<p>We initialize an empty list named <code>ids<\/code> to store the &#8216;id&#8217; field from each document retrieved from MongoDB. Then, we iterate through the cursor and append each &#8216;id&#8217; to the <code>ids<\/code> list.<\/p>\n\n\n\n<p><strong>Plotting:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Plotting\nplt.figure(figsize=(10, 6))  # Setting figure size\nplt.plot(ids)  # Plotting the ids data\nplt.title('ID Data from MongoDB Collection')  # Setting title for the plot\nplt.xlabel('Index')  # Setting label for x-axis\nplt.ylabel('ID')  # Setting label for y-axis\nplt.grid(True)  # Enabling grid lines\nplt.show()  # Displaying the plot<\/code><\/pre>\n\n\n\n<p>Using <code>matplotlib<\/code>, we plot the data stored in the <code>ids<\/code> list. We set labels for the axes, title for the plot, and enable grid lines for better visualization.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"640\" height=\"412\" src=\"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/03\/Data-Visulization.png?resize=640%2C412&#038;ssl=1\" alt=\"\" class=\"wp-image-3012\" srcset=\"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/03\/Data-Visulization.png?w=850&amp;ssl=1 850w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/03\/Data-Visulization.png?resize=300%2C193&amp;ssl=1 300w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/03\/Data-Visulization.png?resize=768%2C494&amp;ssl=1 768w, https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/03\/Data-Visulization.png?resize=420%2C270&amp;ssl=1 420w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><\/figure>\n\n\n\n<p><strong>Exception Handling:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>except Exception as e:\n    print(\"An error occurred:\", e)  # Handling exceptions if any error occurs during the process<\/code><\/pre>\n\n\n\n<p>We include exception handling to catch any errors that might occur during the process of data retrieval or plotting.<\/p>\n\n\n\n<p><strong>Call the Function to Plot Data:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Call the Function to Plot Data\nplot_data()  # Calling the function to execute the code and visualize the data<\/code><\/pre>\n\n\n\n<p>Finally, we call the <code>plot_data()<\/code> function to execute the code and visualize the data from the MongoDB collection.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2024\/03\/27\/visualizing-data-from-mongodb-collection-using-python\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":3014,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[489],"tags":[549,522,502],"class_list":["post-3008","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-driven-applications-using-mongodb-python-and-google-colab","tag-data-visulization","tag-mongodb","tag-python"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/03\/Slide1-9-jpg.webp?fit=1280%2C720&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-Mw","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/3008","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=3008"}],"version-history":[{"count":5,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/3008\/revisions"}],"predecessor-version":[{"id":3015,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/3008\/revisions\/3015"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/3014"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=3008"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=3008"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=3008"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}