Python MongoDB Get Started
Learn how to connect Python with MongoDB database
🚀 Getting Started with MongoDB
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. With Python and PyMongo, you can easily work with MongoDB to build powerful applications.
# Install PyMongo
# pip install pymongo
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["customers"]
print("Connected to MongoDB!")
What is MongoDB?
Document Database
Stores data in JSON-like documents
# Document example
customer = {
"name": "John",
"age": 30,
"city": "New York"
}
Flexible Schema
No fixed table structure required
# Different structures OK
user1 = {"name": "Alice", "age": 25}
user2 = {"name": "Bob", "email": "[email protected]"}
High Performance
Fast queries and scalability
# Fast operations
result = collection.find({"age": {"$gt": 18}})
print(f"Found {result.count()} adults")
Python Integration
Easy to use with PyMongo
# Simple Python integration
import pymongo
client = pymongo.MongoClient()
db = client.myapp
📦 Installation
Before working with MongoDB in Python, you need to install PyMongo
# Install PyMongo using pip
pip install pymongo
# For additional features (optional)
pip install pymongo[srv]
💡 Prerequisites
- Python 3.6 or higher
- MongoDB server installed (local or cloud)
- Basic Python knowledge
🔌 Connecting to MongoDB
Learn how to establish a connection to your MongoDB database
🔹 Local Connection
import pymongo
# Connect to local MongoDB (default port 27017)
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Test the connection
try:
# Ping the server
client.admin.command('ping')
print("✅ Connected to MongoDB successfully!")
except Exception as e:
print(f"❌ Connection failed: {e}")
# Access a database
db = client["mystore"]
print(f"Using database: {db.name}")
🔹 Cloud Connection (MongoDB Atlas)
# Connect to MongoDB Atlas (cloud)
connection_string = "mongodb+srv://username:[email protected]/"
client = pymongo.MongoClient(connection_string)
# Test cloud connection
try:
client.admin.command('ping')
print("✅ Connected to MongoDB Atlas!")
except Exception as e:
print(f"❌ Atlas connection failed: {e}")
🔹 Connection with Options
# Connection with timeout and other options
client = pymongo.MongoClient(
"mongodb://localhost:27017/",
serverSelectionTimeoutMS=5000, # 5 second timeout
connectTimeoutMS=10000, # 10 second connection timeout
maxPoolSize=50 # Max 50 connections
)
print("Connected with custom options!")
📚 MongoDB Basic Concepts
Understanding the key concepts in MongoDB
🏗️ MongoDB Structure
- Database: Container for collections (like a folder)
- Collection: Group of documents (like a table)
- Document: Individual record (like a row)
- Field: Key-value pair in document (like a column)
# Working with databases and collections
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Create/access database
db = client["school"]
# Create/access collection
students = db["students"]
# Example document
student_doc = {
"_id": 1,
"name": "Alice Johnson",
"age": 20,
"grade": "A",
"subjects": ["Math", "Science", "English"]
}
print("Database:", db.name)
print("Collection:", students.name)
print("Document example:", student_doc)
🎯 Your First MongoDB Program
Let's create a simple program that connects to MongoDB and performs basic operations
import pymongo
from datetime import datetime
def main():
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Create database and collection
db = client["tutorial"]
users = db["users"]
# Insert a sample user
user = {
"name": "John Doe",
"email": "[email protected]",
"age": 28,
"created_at": datetime.now()
}
# Insert the document
result = users.insert_one(user)
print(f"✅ User inserted with ID: {result.inserted_id}")
# Find the user
found_user = users.find_one({"name": "John Doe"})
print(f"📄 Found user: {found_user['name']}")
# Count documents
count = users.count_documents({})
print(f"📊 Total users: {count}")
# Close connection
client.close()
print("🔌 Connection closed")
if __name__ == "__main__":
main()