Printing MongoDB Collection’s Data in Python

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 from pymongo 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 as retryWrites and w.

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 the db.*** 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 named collection.
  • 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 the cursor 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.

You can read a detailed tutorial related to MongoDB here.

66 thoughts on “Printing MongoDB Collection’s Data in Python

  1. You’ve made some decent points there. I checked on the
    net to find out more about the issue and found most people
    will go along with your views on this website.

  2. Having read this I believed it was rather enlightening.
    I appreciate you spending some time and energy to put this article together.
    I once again find myself personally spending a significant amount of time
    both reading and posting comments. But so what, it was still worthwhile!

  3. Asking questions are genuinely good thing if you are not
    understanding something entirely, except this article provides
    good understanding yet.

  4. constantly i used to read smaller posts which as
    well clear their motive, and that is also happening with this post which I am reading
    at this place.

  5. Hmm it appears like your website ate my
    first comment (it was super long) so I guess I’ll just
    sum it up what I had written and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring blog blogger but I’m still new to the whole thing.
    Do you have any tips for first-time blog writers? I’d really appreciate it.

  6. Hi are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you need any html coding expertise to make your own blog?
    Any help would be greatly appreciated!

  7. I do not know whether it’s just me or if everyone else encountering problems with your site.
    It seems like some of the written text on your posts are running off
    the screen. Can somebody else please comment and let me know if this is
    happening to them too? This may be a issue with my browser because I’ve had this happen previously.
    Cheers

  8. Hi! I’ve been reading your weblog for a long time
    now and finally got the bravery to go ahead and give you a shout out
    from Kingwood Texas! Just wanted to say keep up the good job!

  9. Hi there! I could have sworn I’ve been to this website before but
    after browsing through some of the post I realized it’s new to
    me. Nonetheless, I’m definitely delighted I found it and I’ll be book-marking and
    checking back often!

  10. https://pg99.it.com/
    I know this if off topic but I’m looking into starting my own weblog and was wondering what all is required
    to get set up? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web savvy so I’m not 100% positive. Any recommendations or advice would be greatly appreciated.
    Thanks

  11. I’ve been surfing on-line more than 3 hours lately, but I
    by no means discovered any interesting article like yours.
    It’s beautiful worth enough for me. In my view, if all site
    owners and bloggers made good content as you probably did, the
    net shall be a lot more helpful than ever before.

  12. I was suggested this web site by my cousin. I am not sure whether this post
    is written by him as nobody else know such detailed about my
    problem. You’re incredible! Thanks!

  13. https://cmanga.org/

    Whats up very nice blog!! Man .. Beautiful .. Amazing ..
    I’ll bookmark your site and take the feeds additionally?
    I’m satisfied to find numerous useful info right here within the
    put up, we’d like work out more strategies in this regard, thank
    you for sharing. . . . . .

  14. Does your website have a contact page? I’m having trouble locating it
    but, I’d like to shoot you an e-mail. I’ve got some recommendations for your blog you
    might be interested in hearing. Either way, great blog and I look forward to seeing it improve over
    time.

  15. Excellent way of describing, and pleasant piece of writing to take facts about my presentation topic,
    which i am going to convey in school.

  16. My family always say that I am killing my time here at web, however I know I am getting familiarity everyday by
    reading such fastidious content.

  17. To be honest, I was looking for Zithromax without waiting and stumbled upon Antibiotics Express. They let you get treatment fast securely. For treating a bacterial infection, try here. Fast shipping guaranteed. More info: amoxil online purchase. Good luck.

  18. To be honest, I wanted to buy Ciprofloxacin urgently and stumbled upon this amazing site. They let you purchase generics online legally. If you have sinusitis, I recommend this site. Discreet packaging to USA. Check it out: buy doxycycline no script. Hope you feel better.

  19. Halo Bosku, lagi nyari situs slot yang hoki? Coba main di Bonaslot. Winrate tertinggi hari ini dan terbukti membayar. Deposit bisa pakai Pulsa tanpa potongan. Login disini: https://bonaslotind.us.com/# Bonaslot login semoga maxwin.

  20. Bocoran slot gacor hari ini: mainkan Gate of Olympus atau Mahjong Ways di Bonaslot. Website ini gampang menang dan resmi. Promo menarik menanti anda. Akses link: п»їlogin sekarang raih kemanangan.

  21. п»їHalo Bosku, cari situs slot yang hoki? Coba main di Bonaslot. Winrate tertinggi hari ini dan pasti bayar. Isi saldo bisa pakai OVO tanpa potongan. Daftar sekarang: п»їhttps://bonaslotind.us.com/# bonaslotind.us.com salam jackpot.

  22. Pin-Up AZ Azərbaycanda ən populyar platformadır. Burada minlərlə oyun və Aviator var. Pulu kartınıza tez köçürürlər. Proqramı də var, telefondan oynamaq çox rahatdır. Rəsmi sayt Pin Up yüklə yoxlayın.

  23. Bu sene popГјler olan casino siteleri hangileri? CevabД± platformumuzda mevcuttur. Bedava bahis veren siteleri ve gГјncel giriЕџ linklerini paylaЕџД±yoruz. Д°ncelemek iГ§in п»їtГјrkГ§e casino siteleri fД±rsatД± kaГ§Д±rmayД±n.

  24. п»їMerhaba arkadaЕџlar, gГјvenilir casino siteleri bulmak istiyorsanД±z, bu siteye mutlaka gГ¶z atД±n. En iyi firmalarД± ve bonuslarД± sizin iГ§in listeledik. GГјvenli oyun iГ§in doДџru adres: п»їbonus veren siteler bol Еџanslar.

  25. Aktual Pin Up giriş ünvanını axtarırsınızsa, bura baxa bilərsiniz. İşlək link vasitəsilə hesabınıza girin və oynamağa başlayın. Xoş gəldin bonusu sizi gözləyir. Keçid: https://pinupaz.jp.net/# Pin Up kazino hamıya bol şans.

  26. Situs Bonaslot adalah bandar judi slot online nomor 1 di Indonesia. Ribuan member sudah merasakan Maxwin sensasional disini. Proses depo WD super cepat hanya hitungan menit. Link alternatif п»їBonaslot link alternatif jangan sampai ketinggalan.

  27. Salam Gacor, cari situs slot yang mudah menang? Rekomendasi kami adalah Bonaslot. RTP Live tertinggi hari ini dan terbukti membayar. Isi saldo bisa pakai Pulsa tanpa potongan. Daftar sekarang: https://bonaslotind.us.com/# Bonaslot rtp semoga maxwin.

  28. Bocoran slot gacor hari ini: mainkan Gate of Olympus atau Mahjong Ways di Bonaslot. Situs ini gampang menang dan aman. Promo menarik menanti anda. Akses link: https://bonaslotind.us.com/# Bonaslot slot dan menangkan.

  29. Selamlar, ödeme yapan casino siteleri bulmak istiyorsanız, bu siteye mutlaka göz atın. Lisanslı firmaları ve bonusları sizin için inceledik. Dolandırılmamak için doğru adres: casino siteleri bol şanslar.

  30. Situs Bonaslot adalah bandar judi slot online nomor 1 di Indonesia. Ribuan member sudah mendapatkan Jackpot sensasional disini. Transaksi super cepat kilat. Situs resmi п»їklik disini jangan sampai ketinggalan.

  31. Info slot gacor hari ini: mainkan Gate of Olympus atau Mahjong Ways di Bonaslot. Website ini anti rungkad dan aman. Promo menarik menanti anda. Akses link: п»їhttps://bonaslotind.us.com/# situs slot resmi dan menangkan.

  32. Bu sene popüler olan casino siteleri hangileri? Detaylı liste web sitemizde mevcuttur. Deneme bonusu veren siteleri ve güncel giriş linklerini paylaşıyoruz. İncelemek için https://cassiteleri.us.org/# casino siteleri fırsatı kaçırmayın.

  33. Situs Bonaslot adalah agen judi slot online terpercaya di Indonesia. Banyak member sudah mendapatkan Maxwin sensasional disini. Transaksi super cepat kilat. Link alternatif Bonaslot daftar jangan sampai ketinggalan.

  34. Bu sene en çok kazandıran casino siteleri hangileri? Cevabı platformumuzda mevcuttur. Deneme bonusu veren siteleri ve yeni adres linklerini paylaşıyoruz. İncelemek için https://cassiteleri.us.org/# siteyi incele kazanmaya başlayın.

  35. CanlД± casino oynamak isteyenler iГ§in rehber niteliДџinde bir site: п»їburaya tД±kla Nerede oynanД±r diye dГјЕџГјnmeyin. OnaylД± bahis siteleri listesi ile rahatГ§a oynayД±n. Detaylar linkte.

  36. п»їHЙ™r vaxtД±nД±z xeyir, Й™gЙ™r siz yaxЕџД± kazino axtarД±rsД±nД±zsa, mГјtlЙ™q Pin Up saytД±nД± yoxlayasД±nД±z. YГјksЙ™k Й™msallar vЙ™ sГјrЙ™tli Г¶dЙ™niЕџlЙ™r burada mГ¶vcuddur. Qeydiyyatdan keГ§in vЙ™ bonus qazanД±n. Oynamaq ГјГ§Гјn link: п»їhttps://pinupaz.jp.net/# Pin-Up Casino uДџurlar hЙ™r kЙ™sЙ™!

  37. Pin-Up AZ Azərbaycanda ən populyar kazino saytıdır. Burada minlərlə oyun və canlı dilerlər var. Qazancı kartınıza tez köçürürlər. Mobil tətbiqi də var, telefondan oynamaq çox rahatdır. Giriş linki https://pinupaz.jp.net/# burada tövsiyə edirəm.

  38. Online slot oynamak isteyenler iГ§in kД±lavuz niteliДџinde bir site: п»їlisteyi gГ¶r Hangi site gГјvenilir diye dГјЕџГјnmeyin. OnaylД± casino siteleri listesi ile rahatГ§a oynayД±n. Detaylar linkte.

  39. Info slot gacor hari ini: mainkan Gate of Olympus atau Mahjong Ways di Bonaslot. Situs ini anti rungkad dan aman. Bonus new member menanti anda. Kunjungi: п»їBonaslot login dan menangkan.

  40. Yeni Pin Up giriş ünvanını axtaranlar, bura baxa bilərsiniz. İşlək link vasitəsilə hesabınıza girin və oynamağa başlayın. Pulsuz fırlanmalar sizi gözləyir. Keçid: Pin Up AZ uğurlar.

  41. Salam Gacor, cari situs slot yang gacor? Coba main di Bonaslot. RTP Live tertinggi hari ini dan pasti bayar. Deposit bisa pakai Pulsa tanpa potongan. Daftar sekarang: klik disini semoga maxwin.

  42. Bu sene en çok kazandıran casino siteleri hangileri? Detaylı liste web sitemizde mevcuttur. Bedava bahis veren siteleri ve yeni adres linklerini paylaşıyoruz. İncelemek için kaçak bahis siteleri fırsatı kaçırmayın.

  43. 2026 yД±lД±nda en Г§ok kazandД±ran casino siteleri hangileri? CevabД± platformumuzda mevcuttur. Bedava bahis veren siteleri ve yeni adres linklerini paylaЕџД±yoruz. Д°ncelemek iГ§in п»їhttps://cassiteleri.us.org/# cassiteleri.us.org fД±rsatД± kaГ§Д±rmayД±n.

  44. Merhaba arkadaşlar, sağlam casino siteleri arıyorsanız, hazırladığımız listeye kesinlikle göz atın. En iyi firmaları ve fırsatları sizin için inceledik. Güvenli oyun için doğru adres: https://cassiteleri.us.org/# en iyi casino siteleri bol şanslar.

  45. Canlı casino oynamak isteyenler için rehber niteliğinde bir site: bonus veren siteler Hangi site güvenilir diye düşünmeyin. Onaylı bahis siteleri listesi ile rahatça oynayın. Detaylar linkte.

  46. Canlı casino oynamak isteyenler için rehber niteliğinde bir site: cassiteleri.us.org Nerede oynanır diye düşünmeyin. Onaylı bahis siteleri listesi ile sorunsuz oynayın. Detaylar linkte.

  47. Salam Gacor, cari situs slot yang hoki? Coba main di Bonaslot. Winrate tertinggi hari ini dan terbukti membayar. Isi saldo bisa pakai OVO tanpa potongan. Login disini: https://bonaslotind.us.com/# Bonaslot rtp semoga maxwin.

  48. Salamlar, siz də keyfiyyətli kazino axtarırsınızsa, mütləq Pin Up saytını yoxlayasınız. Yüksək əmsallar və sürətli ödənişlər burada mövcuddur. İndi qoşulun və ilk depozit bonusunu götürün. Daxil olmaq üçün link: pinupaz.jp.net uğurlar hər kəsə!

Leave a Reply

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