bhylu.com

Advertisements

MongoDB Query

A MongoDB query filter is structured data describing the match. Construct it from validated fields and values rather than accepting arbitrary user-supplied operators.

Understand the idea

The $gte operator includes values at or above a boundary. Validate that a submitted stock threshold is a suitable integer. Keep a fixed allowed query structure so an untrusted mapping cannot quietly become a broader database instruction. Consider missing fields and mixed stored types when defining a filter's intended meaning.

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"]
    query = {"stock": {"$gte": 5}}
    for document in collection.find(query, {"_id": 0}).sort("name", 1):
        print(document)

Read the result

Only documents whose stock matches the server's greater-than-or-equal numeric comparison are printed.

Try one change

Test stock just below and exactly at five in disposable lab documents.

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.