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
pymongo
library, which allows us to interact with MongoDB from Python. - We specifically import the
MongoClient
class frompymongo
to 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
MongoClient
class 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 asretryWrites
andw
.
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-except
block 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 thecursor
variable, which contains the retrieved documents.
# Print names
for document in cursor:
- We iterate over each document in the
cursor
object 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.
236 thoughts on “Printing MongoDB Collection’s Data in Python”
mexican mail order pharmacies: mexican online pharmacy – mexican drugstore online
buying prescription drugs in mexico
http://cmqpharma.com/# п»їbest mexican online pharmacies
mexican online pharmacies prescription drugs
canadian family pharmacy: canadian discount pharmacy – canadian pharmacy world
legit canadian pharmacy: canada online pharmacy – canadian pharmacy no rx needed
mexican pharmaceuticals online: mexico pharmacies prescription drugs – mexico drug stores pharmacies
http://indiapharmast.com/# top 10 pharmacies in india
canadian pharmacy king: canadian pharmacy victoza – buy drugs from canada
http://foruspharma.com/# buying prescription drugs in mexico online
cheapest online pharmacy india: buy prescription drugs from india – india pharmacy
purple pharmacy mexico price list: pharmacies in mexico that ship to usa – mexico pharmacy
mexican online pharmacies prescription drugs: mexican drugstore online – mexico pharmacies prescription drugs
п»їlegitimate online pharmacies india: pharmacy website india – cheapest online pharmacy india
india online pharmacy: reputable indian online pharmacy – indian pharmacies safe
https://foruspharma.com/# buying prescription drugs in mexico online
indian pharmacy: top 10 pharmacies in india – top 10 online pharmacy in india
http://amoxildelivery.pro/# amoxicillin 500 mg where to buy
https://ciprodelivery.pro/# ciprofloxacin 500 mg tablet price
http://ciprodelivery.pro/# where can i buy cipro online
http://paxloviddelivery.pro/# Paxlovid buy online
https://amoxildelivery.pro/# amoxicillin 500mg capsule
https://paxloviddelivery.pro/# buy paxlovid online
http://paxloviddelivery.pro/# Paxlovid over the counter
http://amoxildelivery.pro/# amoxicillin 500mg price
https://clomiddelivery.pro/# how can i get cheap clomid no prescription
https://mexicandeliverypharma.com/# medicine in mexico pharmacies
mexican drugstore online: п»їbest mexican online pharmacies – pharmacies in mexico that ship to usa
best online pharmacies in mexico: mexican border pharmacies shipping to usa – mexican drugstore online
reputable mexican pharmacies online: mexican pharmaceuticals online – medicine in mexico pharmacies
mexican online pharmacies prescription drugs: п»їbest mexican online pharmacies – buying prescription drugs in mexico online
https://mexicandeliverypharma.com/# buying from online mexican pharmacy
mexican drugstore online: best online pharmacies in mexico – reputable mexican pharmacies online
mexican rx online: buying prescription drugs in mexico online – mexican border pharmacies shipping to usa
buying from online mexican pharmacy: mexican pharmaceuticals online – medicine in mexico pharmacies
mexican drugstore online: mexican mail order pharmacies – medication from mexico pharmacy
mexican mail order pharmacies: buying from online mexican pharmacy – buying from online mexican pharmacy
п»їbest mexican online pharmacies: mexico pharmacies prescription drugs – purple pharmacy mexico price list
п»їbest mexican online pharmacies: mexican online pharmacies prescription drugs – medicine in mexico pharmacies
pharmacies in mexico that ship to usa: mexican pharmaceuticals online – mexican border pharmacies shipping to usa
medication from mexico pharmacy: mexican border pharmacies shipping to usa – mexico pharmacies prescription drugs
medication from mexico pharmacy: pharmacies in mexico that ship to usa – best online pharmacies in mexico
mexican pharmaceuticals online reputable mexican pharmacies online medicine in mexico pharmacies
buying prescription drugs in mexico: mexican rx online – mexican mail order pharmacies
mexican drugstore online: buying prescription drugs in mexico – mexico drug stores pharmacies
pharmacies in mexico that ship to usa: mexico pharmacies prescription drugs – п»їbest mexican online pharmacies
mexico pharmacies prescription drugs: reputable mexican pharmacies online – best online pharmacies in mexico
п»їbest mexican online pharmacies: mexican pharmaceuticals online – mexico drug stores pharmacies
mexico pharmacies prescription drugs: reputable mexican pharmacies online – mexican drugstore online
medicine in mexico pharmacies: mexican drugstore online – mexican mail order pharmacies
mexican mail order pharmacies: medication from mexico pharmacy – mexico pharmacies prescription drugs
buying prescription drugs in mexico online: reputable mexican pharmacies online – medication from mexico pharmacy
mexican online pharmacies prescription drugs: best online pharmacies in mexico – mexican mail order pharmacies
mexico drug stores pharmacies: mexican pharmaceuticals online – buying prescription drugs in mexico
mexico pharmacies prescription drugs: mexican pharmaceuticals online – reputable mexican pharmacies online
mexican pharmaceuticals online reputable mexican pharmacies online mexico drug stores pharmacies
mexican online pharmacies prescription drugs: mexican drugstore online – purple pharmacy mexico price list
buying from online mexican pharmacy: mexican mail order pharmacies – buying from online mexican pharmacy
mexico pharmacies prescription drugs: mexican pharmaceuticals online – mexican rx online
purple pharmacy mexico price list: purple pharmacy mexico price list – mexican pharmaceuticals online
п»їbest mexican online pharmacies: medication from mexico pharmacy – mexican border pharmacies shipping to usa
buying prescription drugs in mexico: mexican rx online – mexico drug stores pharmacies
pharmacies in mexico that ship to usa: purple pharmacy mexico price list – reputable mexican pharmacies online
mexico drug stores pharmacies: buying prescription drugs in mexico – п»їbest mexican online pharmacies
mexican online pharmacies prescription drugs: mexico drug stores pharmacies – purple pharmacy mexico price list
buying from online mexican pharmacy: mexico drug stores pharmacies – pharmacies in mexico that ship to usa
mexico drug stores pharmacies: buying prescription drugs in mexico online – buying prescription drugs in mexico online
mexican pharmaceuticals online: mexico drug stores pharmacies – mexican border pharmacies shipping to usa
mexican border pharmacies shipping to usa: mexican border pharmacies shipping to usa – pharmacies in mexico that ship to usa
reputable mexican pharmacies online: mexico drug stores pharmacies – buying from online mexican pharmacy
mexican rx online: best online pharmacies in mexico – medicine in mexico pharmacies
generic zithromax 500mg india: zithromax online pharmacy canada – where can i buy zithromax capsules
https://zithromaxbestprice.pro/# zithromax generic cost
http://nolvadexbestprice.pro/# tamoxifen side effects forum
average cost of generic zithromax: zithromax buy online no prescription – zithromax
http://zithromaxbestprice.pro/# buy zithromax online with mastercard
https://cytotecbestprice.pro/# cytotec online
3000mg prednisone: prednisone pills cost – 10mg prednisone daily
http://zithromaxbestprice.pro/# how to get zithromax online
https://zithromaxbestprice.pro/# zithromax 250 price
prednisone 20mg price: prednisone 7.5 mg – order prednisone online no prescription
buy prednisone without a prescription: prednisone coupon – prednisone 20 mg
http://propeciabestprice.pro/# get generic propecia pill
can i buy zithromax over the counter: zithromax prescription online – can i buy zithromax online
get generic propecia: buy cheap propecia for sale – order propecia no prescription
tamoxifen depression: nolvadex only pct – tamoxifen skin changes
http://zithromaxbestprice.pro/# zithromax 500 mg for sale
get propecia price: order propecia without prescription – buy propecia tablets
cost of cheap propecia: cost of cheap propecia prices – cost of propecia without rx
farmaci senza ricetta elenco: Cialis generico farmacia – Farmacie online sicure
п»їFarmacia online migliore: avanafil in farmacia – п»їFarmacia online migliore
farmacie online sicure: Cialis generico prezzo – Farmacie online sicure
acquistare farmaci senza ricetta: kamagra gel – Farmacia online piГ№ conveniente
farmacia online senza ricetta: Farmacie che vendono Cialis senza ricetta – Farmacia online miglior prezzo
http://tadalafil.auction/# cialis soft tabs canada
https://sildenafil.llc/# generic viagra
https://tadalafil.auction/# buy cialis from cananda
http://indiapharmacy.shop/# indian pharmacy paypal
buying erectile dysfunction pills online
https://mexicopharmacy.win/# mexican online pharmacies prescription drugs
best ed pills online
http://indiapharmacy.shop/# best india pharmacy
https://edpillpharmacy.store/# buy ed medication
get ed prescription online
http://edpillpharmacy.store/# low cost ed pills
http://edpillpharmacy.store/# buy ed meds online
http://edpillpharmacy.store/# erectile dysfunction medications online
https://edpillpharmacy.store/# get ed meds online
http://mexicopharmacy.win/# mexico drug stores pharmacies
http://edpillpharmacy.store/# buy erectile dysfunction pills online
https://indiapharmacy.shop/# world pharmacy india
http://mexicopharmacy.win/# mexican pharmaceuticals online
https://lipitor.guru/# lipitor 10 mg tablet
buy cytotec https://tamoxifen.bid/# п»їdcis tamoxifen
lasix 20 mg
http://lisinopril.guru/# cost for 40 mg lisinopril
lasix side effects furosemide online furosemida 40 mg
buy cytotec in usa http://lisinopril.guru/# buy zestoretic online
lasix side effects
п»їcytotec pills online https://lipitor.guru/# lipitor prescription prices
lasix 40mg
http://lisinopril.guru/# compare zestril prices
nolvadex online buy tamoxifen online tamoxifen cost
Cytotec 200mcg price https://cytotec.pro/# cytotec online
furosemide 100mg
https://lisinopril.guru/# prinivil generic
Abortion pills online https://tamoxifen.bid/# liquid tamoxifen
lasix 100 mg tablet
https://lipitor.guru/# lipitor generic cost
lasix generic: cheap lasix – furosemide 40mg
cytotec pills buy online https://lipitor.guru/# lipitor generic cost
lasix uses
https://tamoxifen.bid/# tamoxifen therapy
http://easyrxcanada.com/# canadian pharmacy oxycodone
http://easyrxcanada.com/# canadian drugstore online
https://mexstarpharma.online/# pharmacies in mexico that ship to usa
https://mexstarpharma.online/# best online pharmacies in mexico
http://mexstarpharma.com/# mexican drugstore online
https://easyrxcanada.com/# pharmacy rx world canada
http://easyrxindia.com/# india pharmacy mail order
http://mexstarpharma.com/# mexican pharmaceuticals online
Your blog has really piqued my interest on this topic. Feel free to drop by my website 92N about Cosmetic Treatment.
bonus veren casino slot siteleri: en iyi slot siteler – slot oyun siteleri
guvenilir slot siteleri: deneme veren slot siteleri – bonus veren casino slot siteleri
https://slotsiteleri.bid/# bonus veren casino slot siteleri
en guvenilir slot siteleri: bonus veren casino slot siteleri – casino slot siteleri
https://slotsiteleri.bid/# slot oyunlar? siteleri
2024 en iyi slot siteleri: yasal slot siteleri – en guvenilir slot siteleri
https://sweetbonanza.network/# sweet bonanza siteleri
https://sweetbonanza.network/# sweet bonanza mostbet
1xbet 1xbet официальный сайт 1xbet скачать
http://1xbet.contact/# 1хбет официальный сайт
1xbet официальный сайт: 1хбет – 1xbet зеркало рабочее на сегодня
1хбет официальный сайт: 1xbet скачать – зеркало 1хбет
http://1xbet.contact/# 1xbet зеркало
1xbet: 1xbet зеркало рабочее на сегодня – зеркало 1хбет
https://vavada.auction/# vavada casino
1вин: 1вин зеркало – 1win
http://pin-up.diy/# pin up казино
пин ап казино: пин ап казино вход – pin up
http://vavada.auction/# вавада зеркало
web rx pharmacy palace: online pharmacy pain medicine – cheapest pharmacy to buy viagra
mail order pharmacy: ro accutane online pharmacy – Zebeta
https://easydrugrx.com/# protonix pharmacy
ventolin pharmacy uk
benicar online pharmacy: viagra in tesco pharmacy – generic cialis uk online pharmacy
fincar from inhouse pharmacy: online pharmacy provigil modafinil – viagra online us pharmacy
nexium mexico pharmacy: asda pharmacy fluconazole – online pharmacy bupropion xl
https://indianpharmacy.company/# best india pharmacy
fincar uk pharmacy: abilify pharmacy assistance – india pharmacy cymbalta
india online pharmacy: top 10 online pharmacy in india – cheapest online pharmacy india
wedgewood pharmacy tacrolimus: allegra pharmacy prices – overseas pharmacy cialis
https://pharmbig24.com/# zyprexa pharmacy
viagra pharmacy 100mg: publix pharmacy lipitor – cialis us pharmacy online
mexico pharmacies prescription drugs mexican pharmaceuticals online best online pharmacies in mexico
http://mexicopharmacy.cheap/# mexican online pharmacies prescription drugs
india pharmacy mail order: indian pharmacies safe – top online pharmacy india
spain pharmacy viagra: giant eagle pharmacy – thorazine online pharmacy
mexican pharmaceuticals online mexico drug stores pharmacies mexican mail order pharmacies
finasteride target pharmacy: avodart pharmacy – closest pharmacy store
http://pharmbig24.com/# viagra tesco pharmacy
indian pharmacy india online pharmacy world pharmacy india
guardian pharmacy ibuprofen: low cost online pharmacy – stromectol online pharmacy
how much does cialis cost at the pharmacy: online medicine tablets shopping – xenical indian pharmacy
http://indianpharmacy.company/# mail order pharmacy india
rx express pharmacy hurley ms: Diamox – best pharmacy
mexican online pharmacies prescription drugs: mexican pharmaceuticals online – mexico drug stores pharmacies
mail order pharmacy india п»їlegitimate online pharmacies india top 10 online pharmacy in india
pharmacy global rx review: save rx pharmacy – stromectol pharmacy
https://mexicopharmacy.cheap/# medicine in mexico pharmacies
buying prescription drugs in mexico reputable mexican pharmacies online medication from mexico pharmacy
top 10 online pharmacy in india: indian pharmacy paypal – top online pharmacy india
buying prescription drugs in mexico online mexico pharmacies prescription drugs pharmacies in mexico that ship to usa
publix pharmacy hours: order cialis online pharmacy – diplomat pharmacy lipitor
https://mexicopharmacy.cheap/# best online pharmacies in mexico
cheapest pharmacy to fill prescriptions without insurance: eckerd pharmacy store locator – lamisil pharmacy uk
reliable rx pharmacy coupon code: antibacterial – cymbalta target pharmacy
mail order pharmacy india: best india pharmacy – online pharmacy india
https://pharmbig24.com/# online international pharmacy
india online pharmacy pharmacy website india п»їlegitimate online pharmacies india
best india pharmacy: indianpharmacy com – reputable indian online pharmacy
mexican online pharmacies prescription drugs: п»їbest mexican online pharmacies – mexican drugstore online
http://pharmbig24.com/# zithromax pharmacy price
https://casibom.auction/# casibom guncel giris
casibom guncel casibom 158 giris casibom guncel
https://casibom.auction/# casibom giris
https://betine.online/# betine
https://casibom.auction/# casibom giris
se puede comprar viagra sin receta: sildenafilo – viagra online cerca de malaga
https://tadalafilo.bid/# п»їfarmacia online espaГ±a
farmacia online 24 horas
sildenafilo 100mg precio farmacia sildenafilo sildenafilo 50 mg precio sin receta
farmacia online barata farmacia online barata farmacia online envГo gratis
http://farmaciaeu.com/# farmacias online seguras en espaГ±a
п»їfarmacia online espaГ±a
farmacia barata: tadalafilo – farmacia online barcelona
http://tadalafilo.bid/# farmacia online envГo gratis
farmacias direct
farmacia online envГo gratis: farmacia online 24 horas – farmacia barata
https://sildenafilo.men/# sildenafilo 100mg precio espaГ±a
farmacia online barata y fiable
top farmacia online: Farmacie online sicure – farmacia online piГ№ conveniente
comprare farmaci online con ricetta Farmacie online sicure Farmacia online piГ№ conveniente
Farmacie on line spedizione gratuita: Farmacia online migliore – farmacia online piГ№ conveniente
Farmacie on line spedizione gratuita: Farmacie online sicure – comprare farmaci online con ricetta
farmacie online affidabili comprare farmaci online con ricetta acquisto farmaci con ricetta
comprare farmaci online all’estero: Cialis generico controindicazioni – top farmacia online
Farmacia online piГ№ conveniente Farmacia online migliore acquistare farmaci senza ricetta
cerco viagra a buon prezzo: viagra farmacia – alternativa al viagra senza ricetta in farmacia
Farmacie online sicure: Tadalafil generico migliore – Farmacia online piГ№ conveniente
farmacia online Farmacie on line spedizione gratuita Farmacie on line spedizione gratuita
comprare farmaci online con ricetta Cialis generico recensioni farmacie online autorizzate elenco
viagra online consegna rapida: acquisto viagra – alternativa al viagra senza ricetta in farmacia
farmacia online senza ricetta Cialis generico controindicazioni Farmacia online miglior prezzo
pillole per erezioni fortissime viagra farmacia viagra 100 mg prezzo in farmacia
Farmacia online miglior prezzo: Farmacie on line spedizione gratuita – Farmacie on line spedizione gratuita
comprare farmaci online con ricetta Brufen antinfiammatorio comprare farmaci online con ricetta
lasix 20 mg: buy furosemide – lasix generic name
lasix 20 mg: buy furosemide online – furosemida
prednisone 10: prednisone 50 mg prices – purchase prednisone 10mg
rybelsus generic: semaglutide – Buy semaglutide pills
ventolin 200 mcg: buy Ventolin – where can i order ventolin without a prescription
pharmacie en ligne fiable pharmacie en ligne france livraison internationale Achat mГ©dicament en ligne fiable
Achat mГ©dicament en ligne fiable Acheter Cialis 20 mg pas cher pharmacie en ligne france fiable
Viagra homme prix en pharmacie viagra sans ordonnance Viagra sans ordonnance pharmacie France
https://pharmaciepascher.pro/# trouver un mГ©dicament en pharmacie
pharmacie en ligne avec ordonnance: pharmacie en ligne pas cher – Pharmacie sans ordonnance
Viagra homme sans prescription Viagra sans ordonnance 24h Viagra pas cher livraison rapide france
Talk to any business owner or executive and ask them how their online chatting with video has changed over the past several years
with me you can have fun on the phone am ready for any outrage. hottest sex chat for free me and have fun.
The best thing is that you can use the live cam technology yourself and interact with the women in the chat – all you need is a free free live sex cams account and your own cam.
If you’re looking for hot live sex and sexcam sex, you’re definitely in good hands here too. In addition to the click for more to connect, we have also included the sex cam providers in this overview to make the offer even more interesting for you as a surfer.