bhylu.com

Advertisements

MongoDB Update

An update can change selected fields without replacing the entire document. Use a fixed filter and an update operator that describes the intended change.

Understand the idea

$inc increments a numeric field on the server, avoiding a separate stale client read followed by a replacement write. A single-document update is atomic under MongoDB's document operation rules; several related documents may require additional coordination or transactions. Check matched_count and modified_count because a request can match nothing or leave a value unchanged.

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"]
    result = collection.update_one({"name": "Desk lamp"}, {"$inc": {"stock": 1}})
    print(result.matched_count, result.modified_count)

Read the result

A matching product should report one match and one modification. With duplicate names, only one matched document is updated.

Try one change

Update by a captured _id and compare the result with a filter that matches no document.

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.