bhylu.com

Advertisements

MongoDB Drop Collection

Dropping a collection removes its documents and indexes. It is a schema-level operation, not the way to delete one selected record.

Understand the idea

This demonstration creates and drops a separately named scratch collection. It does not drop workshop_products. Check the server, database, and identifier before any real drop. Database backups and operational recovery need their own tested procedures; a Python exception handler cannot recreate deleted production data automatically.

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"]
    scratch = database["bhylu_disposable_notes"]
    scratch.insert_one({"note": "temporary"})
    scratch.drop()
    print("bhylu_disposable_notes" in database.list_collection_names())

Read the result

The output is False after the scratch collection is removed.

Try one change

Compare collection drop with deleting only the scratch document and identify what metadata would remain.

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.