Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python meets MongoDB
EXPERIMENT 90 / 101

Give documents an identity.

Insert a structured document and use stable application fields deliberately.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

01 The idea

BSON supports structured documents and additional data types beyond JSON. Every MongoDB document has an _id field that is unique within its collection. If omitted, the driver normally creates an ObjectId. Schema flexibility does not mean application values should be inconsistent: decide required fields, types, and identity rules before writing documents.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

mongodb_documents.py
from lab_support import mongo_lab

with mongo_lab() as collection:
    result = collection.insert_one({"_id": 5, "project": "Atlas", "name": "Document", "minutes": 10, "done": False, "tags": ["writing"]})
    print(result.inserted_id)
    print(collection.count_documents({}))
↳ EXPECTED OUTPUT
5
5

03 Under the hood

  1. 1

    An explicit integer _id makes the teaching result deterministic. Production applications often use generated ObjectId values or another intentional identifier strategy.

  2. 2

    Insert result objects describe write acknowledgement and identifiers. They are not the inserted document itself.

  3. 3

    Validate incoming fields before insertion and consider collection validation rules for shared databases. JSON serializers do not automatically understand every BSON type, including ObjectId and datetime.

04 Your turn, builder

A SMALL MISSION

Insert two deterministic documents with insert_many and print their inserted ids.

Reveal one possible solution +
one_possible_solution.py
from lab_support import mongo_lab

with mongo_lab() as collection:
    result = collection.insert_many([{"_id": 5, "name": "Document", "minutes": 10}, {"_id": 6, "name": "Ship", "minutes": 5}])
    print(result.inserted_ids)

05 Check your signal

QUICK SIGNAL CHECK

What does _id identify?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.