MongoDB Find
find reads documents matching a filter. A projection chooses which fields appear in the result, making the application's expected shape clearer.
Understand the idea
find returns a cursor that is consumed as it is iterated. An empty filter matches all documents. This example excludes _id only for a compact display; real application identifiers are often useful. Add ordering when a user-facing list needs a stable sequence and avoid loading an unbounded large collection into memory.
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"]
for document in collection.find({}, {"_id": 0, "name": 1, "stock": 1}).sort("name", 1):
print(document)
Read the result
The script prints the current lab products with only name and stock fields.
Try one change
Use find_one with a missing name and add an explicit no-result path.
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.