Give documents an identity.
Insert a structured document and use stable application fields deliberately.
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.
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({}))5 5
03 Under the hood
- 1
An explicit integer _id makes the teaching result deterministic. Production applications often use generated ObjectId values or another intentional identifier strategy.
- 2
Insert result objects describe write acknowledgement and identifiers. They are not the inserted document itself.
- 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
Insert two deterministic documents with insert_many and print their inserted ids.
Reveal one possible solution +
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
What does _id identify?
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 ↗.