Guide 11 · Relational and Document Databases

PyMongo and Beanie, Deep Dive

MongoDB from Python: queries without SQL, and typed documents through an asynchronous mapper.

Complete 16 notebooks 16 written

Before this guide: APIs and JSON.

The notebooks

Open in Colab runs a notebook in your browser, and Read shows it on GitHub without running it. Every notebook runs on its own, and the answers to its exercises are in a separate notebook, linked as Solutions.

1Why DocumentsOne object instead of five tables, and a MongoDB running inside this notebookOpen in ColabReadSolutions
2Collections and Documentsinsert_one, insert_many, the _id you did not choose, and the collection a typo inventsOpen in ColabReadSolutions
3BSON TypesThe set you cannot store, the datetime that comes back naive, and the ObjectId json.dumps refusesOpen in ColabReadSolutions
4find and find_oneOne document against a cursor you can walk only once, and a projection that keeps it smallOpen in ColabReadSolutions
5Query OperatorsWhy {'size': {'w': 1}} matches nothing when {'size.w': 1} matches every document where w is 1Open in ColabReadSolutions
6Update Operators$set against the replacement that dropped every other field, and the upsert that inserted a second copyOpen in ColabReadSolutions
7Bulk Writes and Transactionsbulk_write, ordered against unordered, and the write you forgot to pass the session toOpen in ColabReadSolutions
8IndexesCompound order, explain, $text, and the unique index that refuses to buildOpen in ColabReadSolutions
9The Aggregation Pipeline$match, $group, $unwind, and the stage order that decides how long it runsOpen in ColabReadSolutions
10Modeling Without JoinsEmbed until the document will not fit, and the $lookup that scans because the foreign field has no indexOpen in ColabReadSolutions
11Beanie DocumentsA Pydantic model that is also a collection, init_beanie, and the await a Colab cell already allowsOpen in ColabReadSolutions
12Async Queriesfind, to_list, beanie.operators, and the projection model that will not validateOpen in ColabReadSolutions
13Saving Changesset and inc against save, save_changes, and the revision that moved under youOpen in ColabReadSolutions
14Link and BackLinkLink, BackLink, fetch_links, and the single $lookup pipeline that saves a round trip per documentOpen in ColabReadSolutions
15Migrationsbeanie new-migration, iterative against free fall, and the replica set beanie migrate assumesOpen in ColabReadSolutions
16A Product CatalogOne real job: loaded with PyMongo, indexed for the queries it serves, typed with BeanieOpen in ColabReadSolutions