MongoDB Delete
delete_one removes at most one matching document. Use an identifier to make the target precise when names are not unique.
Understand the idea
The script creates a disposable document, captures its _id, then deletes only that identifier. The result reports deleted_count, which should be checked rather than assuming a successful network call found a target. Authorization, retention, and recovery policies are separate responsibilities in a real application.
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"]
temporary_id = collection.insert_one({"name": "Disposable", "stock": 0}).inserted_id
result = collection.delete_one({"_id": temporary_id})
print(result.deleted_count)
Read the result
The expected count is 1. Other lab documents remain.
Try one change
Repeat the same identifier deletion and explain how the zero-count result should be handled.
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.