MongoDB Insert
insert_one writes a document and returns an insertion result. Let the driver manage identifiers unless your model has a deliberate external-key policy.
Understand the idea
A document stores named values, and the driver can add an _id if none was supplied. Repeating insert_one creates another record; retries need an idempotency design when duplicates would be harmful. Keep prices, quantities, and dates represented consistently across documents rather than converting everything to display strings.
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"]
result = collection.insert_one({"name": "Desk lamp", "stock": 8})
print(result.inserted_id)
Read the result
The printed ObjectId identifies the new document. Its exact value changes for each ordinary insert.
Try one change
Insert a second product and retrieve it by the returned identifier instead of assuming the first matching name is unique.
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.