Connect PyMongo to MongoDB
Learn how to connect PyMongo to a running MongoDB instance in this hands-on tutorial. Step-by-step instructions, troubleshooting tips, and what to study next.
Focus: connect pymongo to a running mongodb instance
You've built your models, your API is ready, and now you're staring at a wall between Python and your data: how do you actually connect PyMongo to a running MongoDB instance? Without this connection, none of your queries matter. This lesson strips away the mystery, giving you the exact commands and mistake-prone details to bridge Python and MongoDB so you can start storing and fetching real documents.
The problem this lesson solves
Every MongoDB tutorial assumes you can already talk to the database. But when you try on your own, you're hit with ServerSelectionTimeoutError, wrong ports, or the dreaded "Connection refused." Even if you know MongoDB is installed, you might not know which package to install, what connection string to use, or how to verify the connection works.
This is a classic wiring problem: the database runs in one process, your Python script runs in another, and they need a handshake. Without this lesson, you'll waste hours guessing. With it, you'll connect in under five minutes and move on to actually building your application.
Core concept / mental model
Think of MongoDB as a hotel. The database server (mongod) is the hotel building — it accepts guests (connections) at a specific front desk (the port, default 27017). The PyMongo driver is your concierge: it knows the hotel's address, knocks on the door, and once welcomed, can fetch anything from the rooms (collections).
PyMongo's MongoClient is not a single connection. It manages a connection pool — a set of reusable sockets to the server. This is key: you create one MongoClient object and reuse it across your app. Creating a new client for every query would be like calling a taxi for every block you walk — expensive and slow.
Pro tip: The default port for MongoDB is
27017. If you see28017, that's usually the web interface, not the database protocol.
How it works step by step
- Install PyMongo in your Python environment:
pip install pymongo. You might also wantdnspythonfor SRV connection strings (like MongoDB Atlas). - Start MongoDB in the background or another terminal: the
mongodservice must be running. On macOS/Linux,brew services start mongodb-communityorsudo systemctl start mongod; on Windows, run themongod.exebinary. - Build your connection string: typically
mongodb://localhost:27017/for a local instance. For Atlas, it looks likemongodb+srv://user:pass@cluster.mongodb.net/. - Create a
MongoClient:client = MongoClient(connection_string). This doesn't actually connect yet — it's lazy, the real handshake happens on your first operation. - Access your database and collections: use
client['mydatabase']anddb['mycollection']— no need to pre-create them. - Test the connection with
client.admin.command('ping')and then perform operations likeinsert_oneandfind.
Pro tip: Always use a single
MongoClientper application process. MongoDB drivers are thread-safe and the client manages its own connection pool for you.
Hands-on walkthrough
Let's build a complete example from scratch.
Step 1: Install PyMongo
pip install pymongo
If you're using MongoDB Atlas (cloud), also install dnspython:
pip install dnspython
Step 2: Ensure MongoDB is running
Before you write any Python, verify the server is up. A quick mongosh test prints ok: 1 if the server is healthy:
mongosh --eval "db.runCommand({ping:1})"
If you get an error, your mongod process isn't running. Start it via your system's service manager.
Step 3: Connect from Python
Save this as connect.py:
from pymongo import MongoClient
# Step 1: Build the connection string
connection_string = "mongodb://localhost:27017/"
# Step 2: Create a client (lazy connection)
client = MongoClient(connection_string)
# Step 3: Verify the connection by pinging the server
client.admin.command("ping")
print("Connected to MongoDB!")
Expected output:
Connected to MongoDB!
If you see a ServerSelectionTimeoutError, check that MongoDB is actually running and that the host/port are correct.
Step 4: Read and write a document
Now let's make it useful. We'll insert a user document and immediately read it back:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["shop"] # database (created on first use)
users = db["users"] # collection (also lazy)
# Insert a document
result = users.insert_one({"name": "Ada", "role": "admin"})
print("Inserted id:", result.inserted_id)
# Read it back
user = users.find_one({"name": "Ada"})
print("Found:", user)
Expected output:
Inserted id: 64b6f1c2d3e4f5a6b7c8d9e0
Found: {'_id': ObjectId('64b6f1c2d3e4f5a6b7c8d9e0'), 'name': 'Ada', 'role': 'admin'}
Step 5: Handle authentication
For production, you'll likely have credentials. Here's a connection string with a username and password (URL-encoded if necessary):
from pymongo import MongoClient
# Note: escape special characters in password using URL encoding
conn = "mongodb://admin:mysecretpassword@localhost:27017/"
client = MongoClient(conn)
# If your auth DB is not the default 'admin', specify it
client = MongoClient(conn, authSource="admin")
client.admin.command("ping")
print("Authenticated and connected!")
Pro tip: Keep your connection string in an environment variable, never hardcode it. Use
os.environ["MONGODB_URI"]in production.
Compare options / when to choose what
| Connection type | When to use | Pros | Cons |
|---|---|---|---|
mongodb://localhost:27017/ |
Local development | Fast, no config | Not accessible from other hosts |
mongodb+srv:// (Atlas) |
Cloud / production | Handles replica set discovery automatically | Requires internet, uses SRV DNS |
mongodb://<host>:<port> with replica set |
Multi-node cluster | Explicit control | Harder to configure manually |
Alternative connection approaches:
- Environment variables: Store connection strings in
.envfiles instead of code. - URI builder libraries: Use
pymongo.uri_parseror Django/Flask extensions to build connection strings dynamically. - Other drivers: If you're not using Python, the official drivers for Node.js, Go, etc., use the same MongoDB connection protocol.
Troubleshooting & edge cases
| Symptom | Likely cause | Fix |
|---|---|---|
ServerSelectionTimeoutError |
MongoDB not running or wrong host/port | Start mongod; verify with mongosh; check the URI |
AuthenticationFailed |
Wrong credentials or authSource | Double-check user/password; set authSource to the database where the user was created |
pymongo.errors.ConfigurationError |
Invalid URI syntax | Use mongodb:// or mongodb+srv:// correctly; escape special chars in password |
Connection refused |
Port blocked or service not listening | Use lsof -i :27017 to check; restart service |
| Slow first query | Client is lazy; handshake happens on first operation | Expect a small delay; reusing the same client avoids it |
| Wrong DB or collection | Name typos or default connection | Always access via client["db"]["coll"] explicitly |
Common pitfalls:
- Forgetting to install
dnspythonfor SRV URIs (Atlas). - Creating a new
MongoClientinside every request — leaks sockets. - Using
client = MongoClient("localhost")without the port — defaults to 27017, which is fine, but a common mistake is usinglocalhostvs127.0.0.1in IPv6 environments.
What you learned & what's next
Now you can connect PyMongo to a running MongoDB instance — you've installed the driver, verified the server is alive, performed insert and find operations, and handled authentication and common errors. That's the foundation for every subsequent MongoDB lesson.
Next up in the MongoDB track: you'll dive into CRUD operations in depth — crafting filters, sorting results, and updating documents efficiently. With a working connection, you're ready to manipulate real data with confidence.
Practice recap
Now that you can ping your MongoDB, write a small script that connects to your local instance, creates a books collection, inserts two records, and retrieves one with a filter. Then try intentionally breaking the URI to see the ServerSelectionTimeoutError and practice fixing it. This will make the connection muscle memory.
Common mistakes
- Starting a new MongoClient for every query instead of reusing one — it wastes resources and can exhaust connection pools.
- Forgetting to install
dnspythonwhen usingmongodb+srv://connection strings, causing aConfigurationError. - Typing the host as
localhostwhen MongoDB is bound to127.0.0.1and your system resolves IPv6 first — use127.0.0.1explicitly. - Hardcoding credentials in source code; always pull from environment variables.
Variations
- Use
MongoClient("localhost", 27017)positional arguments instead of a URI string if you prefer explicit parameters. - Connect to a remote instance by replacing
localhostwith the machine's IP or DNS name in the connection string. - Use
mongodb+srv://with MongoDB Atlas for automatic replica set discovery and TLS.
Real-world use cases
- A FastAPI app connects to its MongoDB database on startup using a single MongoClient to handle user sessions and data.
- A data pipeline batches inserts from Python into a shared MongoDB instance configured with authentication and a replica set.
- A microservice uses PyMongo to connect to an Atlas cluster via SRV URI to store event logs for real-time analytics.
Key takeaways
- The PyMongo driver uses MongoClient to manage a connection pool; reuse one client per application.
- A connection string of
mongodb://localhost:27017/connects to your local instance; the server must be running first. - Test connectivity with
client.admin.command("ping")before executing application queries. - Use
mongodb+srv://for Atlas and always installdnspythonfor that URI format. - Databases and collections are created lazily — access them by name and they appear on first insert.
- Store credentials in environment variables, never hardcode them.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.