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
2. Import the Library
import pymongo
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>"
4. Create a MongoDB Client
client = pymongo.MongoClient(CONNECTION_URL)
5. Access Database and Collection
database = client[DB_NAME]
collection = database[COLLECTION_NAME]
6. Insert Data
You can insert one or many documents:
students = [
{"name": "sajjad", "age": 25},
# ... more students ...
]
collection.insert_many(students)
7. Retrieve Data
records = collection.find()
for record in records:
print(record)
8. Convert to DataFrame (Optional)
For analysis, convert the data to a pandas DataFrame:
import pandas as pd
df = pd.DataFrame(list(collection.find()))
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)