
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 plottingThis 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 AtlasThis 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 databaseHere, 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 processThis 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 collectionWe 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 listWe 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 plotUsing 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 processWe 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 dataFinally, we call the plot_data() function to execute the code and visualize the data from the MongoDB collection.
16 thoughts on “Visualizing Data from MongoDB Collection using Python”
어제 친구들과 회식 자리로강남가라오케추천다녀왔는데, 분위기도 좋고 시설도 깨끗해서 추천할 만했어요.
요즘 회식 장소 찾는 분들 많던데, 저는 지난주에강남가라오케추천코스로 엘리트 가라오케 다녀와봤습니다.
분위기 있는 술자리 찾을 땐 역시강남하퍼추천확인하고 예약하면 실패가 없더라고요.
회사 동료들이랑강남엘리트가라오케방문했는데, VIP룸 덕분에 프라이빗하게 즐길 수 있었어요.
신논현역 근처에서 찾다가강남룸살롱를 예약했는데, 접근성이 좋아서 만족했습니다.
술자리도 좋지만 요즘은강남셔츠룸가라오케이라고 불릴 만큼 서비스가 좋은 곳이 많더군요.
When someone writes an piece of writing he/she retains the
plan of a user in his/her mind that how a user can know it.
Therefore that’s why this paragraph is outstdanding. Thanks!
My webpage – Roxie
Thanks for ones marvelous posting! I seriously enjoyed reading it, you’re a great author.
I will be sure to bookmark your blog and will eventually come back someday.
I want to encourage you to continue your great job, have a nice weekend!
Wow, baru tau nih ada Luxury12!
Katanya ini website kelas atas buat pecinta game,
pengalaman bermainnya top banget dan peluang cuannya gede.
Aku kemarin coba sendiri,
dan ternyata fair play banget.
Sangat cocok buat yang serius main game.
Kalau kalian mau coba, cek situsnya,
soalnya lagi rame banget.
Wedee!!
Review my blog Luxury12 login
Marvelous, what a web site it is! This blog gives valuable
facts to us, keep it up.
Hello, i think that i saw you visited my website so i came to “return the favor”.I’m trying to find things to enhance
my site!I suppose its ok to use a few of your ideas!!
Generally I don’t read post on blogs, however
I would like to say that this write-up very compelled me to check out and do it!
Your writing style has been amazed me. Thank you,
very nice article.
Can you tell us more about this? I’d like to find out some additional
information.
Simply want to say your article is as astonishing.
The clarity in your post is simply great and i could assume you’re an expert
on this subject. Fine with your permission let me to grab your feed to keep updated with forthcoming post.
Thanks a million and please carry on the gratifying work.
Do you mind if I quote a couple of your articles as long as I provide credit
and sources back to your webpage? My blog is
in the exact same niche as yours and my users would truly benefit from some of the information you present here.
Please let me know if this okay with you. Thanks a lot!
I have been exploring for a little for any high quality articles
or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site.
Studying this info So i am glad to express that I’ve a very good uncanny feeling I came upon just
what I needed. I such a lot undoubtedly will make certain to do not overlook this site and provides it a
glance regularly.