DEV Community

Sajjad Rahman
Sajjad Rahman

Posted on

MongoDB Connection Workflow in Python

This guide explains the step-by-step workflow for connecting to MongoDB using Python and performing basic operations.

1. Install Required Library

You need the pymongo library to connect Python with MongoDB:

pip install pymongo
Enter fullscreen mode Exit fullscreen mode

2. Import the Library

import pymongo
Enter fullscreen mode Exit fullscreen mode

3. Set Up Connection Parameters

Define your database name, collection name, and connection URL:

DB_NAME = "TEST"
COLLECTION_NAME = "personal_info"
CONNECTION_URL = "mongodb+srv://<username>:<password>@<cluster-url>"
Enter fullscreen mode Exit fullscreen mode

4. Create a MongoDB Client

client = pymongo.MongoClient(CONNECTION_URL)
Enter fullscreen mode Exit fullscreen mode

5. Access Database and Collection

database = client[DB_NAME]
collection = database[COLLECTION_NAME]
Enter fullscreen mode Exit fullscreen mode

6. Insert Data

You can insert one or many documents:

students = [
    {"name": "sajjad", "age": 25},
    # ... more students ...
]
collection.insert_many(students)
Enter fullscreen mode Exit fullscreen mode

7. Retrieve Data

records = collection.find()
for record in records:
    print(record)
Enter fullscreen mode Exit fullscreen mode

8. Convert to DataFrame (Optional)

For analysis, convert the data to a pandas DataFrame:

import pandas as pd
df = pd.DataFrame(list(collection.find()))
Enter fullscreen mode Exit fullscreen mode

Summary

  • Install pymongo
  • Import and set up connection
  • Access database and collection
  • Insert and retrieve data
  • (Optional) Convert to DataFrame for analysis

This workflow helps you quickly connect and interact with MongoDB from Python.

Top comments (0)