Official MongoDB driver for Python · documents & aggregation · verified against PyMongo 4.17 (2026)

PyMongo cheat sheet

PyMongo is the official Python driver for MongoDB — a document database where rows are JSON-like dicts (BSON) and tables are "collections". No fixed schema, no SQL: you insert dicts, query with dict filters and $-operators, and transform with the aggregation pipeline. PyMongo 4.13+ ships a native async client (AsyncMongoClient) that supersedes Motor. This sheet targets PyMongo 4.17 (MongoDB 4.2–8.0, Python 3.9+).

connect insert & query update & delete aggregate & index transactions & async gotcha most common

Verified 2026-08-24 against the official docs at pymongo.readthedocs.io & mongodb.com/docs (PyMongo 4.17.0, 2026-04). Supports MongoDB 4.2–8.0 and Python 3.9+. The async API is stable since 4.13; Motor is being retired in favor of AsyncMongoClient.

Outline

MongoClient → pick a db["collection"]insert_one / find with dict filters → update_one with $-operators. Then aggregation, indexes, transactions, and async.

Connect & read

  1. 1 · Install & connect
  2. 2 · Collections & insert
  3. 3 · Query with find

Modify & shape

  1. 4 · Update & delete
  2. 5 · Aggregation pipeline
  3. 6 · Indexes & bulk

Power & ship

  1. 7 · Transactions
  2. 8 · Async
  3. 9 · Gotchas
  4. Worth memorizing

Connect & read

Open a client, insert documents, and query them back.

1Install & connect4.17
2Collections & insertdatabases are dicts of dicts
3Query with finddict filters + $-operators

Modify & shape

Change documents, aggregate them, and index for speed.

4Update & deleteupdate operators
5Aggregation pipelinetransform & group
6Indexes & bulkspeed + batched writes

Power & ship

Multi-document transactions and the native async client.

7Transactionsmulti-doc atomicity
8AsyncAsyncMongoClient (supersedes Motor)
!Common gotchasread before shipping

Worth memorizing

MongoClient(uri) — one per apppool, thread-safe, lazy connect
db["coll"] created on first writeno schema, no CREATE
insert_one / insert_many.inserted_id / .inserted_ids (ObjectId)
find(filter, projection)lazy cursor; .sort/.limit/.skip
$gt $in $or $exists $regexquery operators in the filter dict
update_one(f, {"$set": ...})operators required; upsert=True
aggregate([{$match},{$group},...])$lookup = join, $unwind = explode
create_index(field, unique=True)else full collection scan
bulk_write([InsertOne, UpdateOne])one round-trip; ordered=False
start_session + with_transactionpass session= to each op; needs replica set
AsyncMongoClient + awaitnative async, supersedes Motor
ObjectId(hex) to query by _id_id is not a string