Printing MongoDB Collection’s Data in Python

Afzal Badshah, PhD
4 min readMar 20, 2024

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({}, {"_id": 0, "name": 1})
        # 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({}, {"_id": 0, "name": 1})
  • 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.

--

--

Afzal Badshah, PhD

Dr Afzal Badshah focuses on academic skills, pedagogy (teaching skills) and life skills.