MongoDB Collection
A collection groups documents in MongoDB. You can create it explicitly when setup needs to be visible or when options must be supplied.
Understand the idea
Documents may have different fields unless you configure validation, so define an application shape even when the server is flexible. This example creates workshop_products only if absent. That check is convenient for a single-user lab, but concurrent setup can race; production creation should handle the server's collection-exists result explicitly.
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
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"]
name = "workshop_products"
if name not in database.list_collection_names():
database.create_collection(name)
print(name)
Read the result
The collection exists after the operation, assuming the lab account has permission.
Try one change
Write down the required fields and types of one workshop product document before adding records.
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.