bhylu.com

Advertisements

MongoDB Get Started

PyMongo connects Python to a MongoDB server. The server and driver are separate installations; importing the driver does not start a database.

Understand the idea

Install pymongo in a local virtual environment. Set MONGODB_URI to a suitable local lab connection string. A MongoClient opens connections lazily, so an explicit ping makes the connectivity check visible. Set a selection timeout so a missing server does not leave a beginner wondering whether the script has stopped working.

Where to try it

Use a local Python environment with pymongo and your own separate MongoDB lab server. Set the lab connection through the environment, as shown below. The online runner does not provide this server connection.

A worked example

Python

import os
from pymongo import MongoClient
with MongoClient(os.environ["MONGODB_URI"], serverSelectionTimeoutMS=3000) as client:
    database = client["bhylu_python_lab"]
    collection = database["workshop_products"]
    print(client.admin.command("ping")["ok"])

Read the result

A reachable authorized server returns an ok value equivalent to 1. A missing or inaccessible server raises a connection-related exception.

Try one change

Stop the lab server and inspect the bounded connection failure, then restart it and compare.

Local MongoDB lab

Install pymongo in your local virtual environment and run a separate MongoDB lab server. Set MONGODB_URI in the environment of the Python process. These examples use bhylu_python_lab and workshop_products; create a few lab products before read/update lessons. Network and server operations are not available in the restricted online runner. The snippets are syntax-checked, not claimed to have been executed against your server.