
Printing MongoDB Collection’s Data in Python
In this tutorial, we’ll walk through the process of connecting to MongoDB Atlas, a cloud-based MongoDB service, from a Python environment. We’ll establish a connection to MongoDB Atlas, select a database and collection, retrieve data from the collection, and print it to the console using the pymongo library. This tutorial is suitable for beginners who are new to MongoDB and Python programming.
Printing Collection
Complete Program:
# Import the Required Libraries
import pymongo
from pymongo import MongoClient
# Connect to MongoDB Atlas
client = pymongo.MongoClient("mongodb+srv://****:****@cluster0.ergtejf.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")
# Select the Database and Collection
db = client.***
collection = db.***
# Define a Function to Print Collection Data
def print_collection_data():
try:
# Retrieve data from MongoDB Atlas
cursor = collection.find()
# Print data
for document in cursor:
print(document)
except Exception as e:
print("An error occurred:", e)
# Call the Function to Print Collection Data
print_collection_data()Step 1: Import the Required Libraries
import pymongo
from pymongo import MongoClient- We import the
pymongolibrary, which allows us to interact with MongoDB from Python. - We specifically import the
MongoClientclass frompymongoto establish a connection to the MongoDB server.
Step 2: Connect to MongoDB Atlas
client = pymongo.MongoClient("mongodb+srv://***:***@cluster0.ergtejf.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")- We use the
MongoClientclass to establish a connection to the MongoDB Atlas cluster. - The connection string
"mongodb+srv://..."specifies the MongoDB Atlas URI, including the username, password, cluster address, and other parameters such asretryWritesandw.
Step 3: Select the Database and Collection
db = client.***
collection = db.***- We select the database named *** using the
client.*** syntax. - Similarly, we select the collection named
***within the *** database using thedb.***syntax.
Step 4: Define a Function to Print Collection Data
def print_collection_data():
try:
# Retrieve data from MongoDB Atlas
cursor = collection.find()
# Print data
for document in cursor:
print(document)
except Exception as e:
print("An error occurred:", e)- We define a function named
print_collection_data()to encapsulate the logic for printing collection data. - Inside the function, we use a
try-exceptblock to handle exceptions that may occur during data retrieval. - We use the
collection.find()method to retrieve all documents from the specified collection. - We iterate over the cursor returned by
find()and print each document to the console.
Step 5: Call the Function to Print Collection Data
print_collection_data()- We call the
print_collection_data()function to execute the logic defined within it. - This step triggers the connection to MongoDB Atlas, retrieval of data from the specified collection, and printing of the collection data to the console.
Printing Selected Columns Data
def print_names():
try:
# Retrieve data from MongoDB Atlas with projection for 'name' field
cursor = collection.find()
# Print names
for document in cursor:
print(document['name'])
except Exception as e:
print("An error occurred:", e)
# Call the Function to Print Names from Collection
print_names()Explanation
Here’s the explanation of each line of the above code:
# Define a Function to Print Names from Collection
def print_names():- We define a Python function named
print_names()that will be responsible for retrieving and printing names from the MongoDB collection.
try:- We begin a try block to handle potential exceptions that may occur during the execution of the code inside the block.
# Retrieve data from MongoDB Atlas with projection for 'name' field
cursor = collection.find()- We use the
find()method to retrieve data from the MongoDB collection namedcollection. - We specify an empty filter
{}as the first parameter to retrieve all documents in the collection. - In the second parameter, we specify the projection to include only the ‘name’ field and exclude the ‘_id’ field.
{ "_id": 0, "name": 1 }. - The result of the
find()method is assigned to thecursorvariable, which contains the retrieved documents.
# Print names
for document in cursor:- We iterate over each document in the
cursorobject using a for loop.
print(document['name'])- Inside the loop, we print the value of the ‘name’ field from each document using dictionary access (
document['name']).
except Exception as e:
print("An error occurred:", e)- If any exceptions occur during the execution of the try block, they will be caught here.
- We print an error message along with the exception that occurred.
# Call the Function to Print Names from Collection
print_names()- We call the
print_names()function to execute the code defined within it and print the names from the MongoDB collection.
This code defines a function print_names() to retrieve and print names from a MongoDB collection and then calls this function to execute the retrieval and printing process.
6 thoughts on “Printing MongoDB Collection’s Data in Python”
어제 친구들과 회식 자리로강남가라오케추천다녀왔는데, 분위기도 좋고 시설도 깨끗해서 추천할 만했어요.
요즘 회식 장소 찾는 분들 많던데, 저는 지난주에강남가라오케추천코스로 엘리트 가라오케 다녀와봤습니다.
분위기 있는 술자리 찾을 땐 역시강남하퍼추천확인하고 예약하면 실패가 없더라고요.
회사 동료들이랑강남엘리트가라오케방문했는데, VIP룸 덕분에 프라이빗하게 즐길 수 있었어요.
신논현역 근처에서 찾다가강남룸살롱를 예약했는데, 접근성이 좋아서 만족했습니다.
술자리도 좋지만 요즘은강남셔츠룸가라오케이라고 불릴 만큼 서비스가 좋은 곳이 많더군요.