Python PyMongo
last modified November 17, 2026 Python 3.15
In this article we show how to work with MongoDB in Python using the PyMongo driver.
MongoDB is a cross-platform, document-oriented NoSQL database. It is developed by MongoDB Inc. and the Community Server is available free of charge under the Server Side Public License.
A record in MongoDB is a document, a data structure composed of field and value pairs. Documents are similar to JSON objects; the values of fields may include other documents, arrays, and arrays of documents. MongoDB stores documents in collections, which are analogous to tables in relational databases, while documents are analogous to rows. Unlike tables, collections do not require all documents to have the same fields. Internally, documents are stored in BSON, a binary format that extends JSON with types such as dates, binary data, and 64-bit integers.
PyMongo is the official MongoDB driver for Python. It provides
the MongoClient class for synchronous code and the
AsyncMongoClient class for asyncio. Documents
are represented as Python dictionaries.
The examples were tested with Python 3.15, PyMongo 4.20, and MongoDB 8.3 on Linux.
Starting MongoDB
For the examples, we run MongoDB in a Docker container. Transactions and
change streams, which we use at the end of the article, need a replica
set. A replica set normally consists of several servers that keep copies of
the data; for development, a set with a single member is enough. We start
the server with the --replSet option and initiate the set with
the mongosh shell, which is included in the image.
The member is registered as localhost:27017. PyMongo
connects to the address that the replica set reports, so the address must
be reachable from the host where our programs run.
$ docker run -d --name mongo -p 27017:27017 mongo:8 --replSet rs0
$ docker exec mongo mongosh --quiet --eval "rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'localhost:27017'}]})"
{
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1794951058, i: 1 }),
signature: {
hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
keyId: Long('0')
}
},
operationTime: Timestamp({ t: 1794951058, i: 1 })
}
$ docker exec mongo mongosh --quiet --eval 'db.hello().isWritablePrimary'
true
Installing PyMongo
PyMongo is installed with pip. The package also contains the
bson module.
$ pip install pymongo
Connecting to MongoDB
The MongoClient class represents a connection to a MongoDB
deployment.
import pymongo
from pymongo import MongoClient
print(pymongo.version)
with MongoClient('mongodb://localhost:27017/') as client:
print(client.admin.command('ping')['ok'])
print(client.address)
info = client.server_info()
print(info['version'])
The example connects to the server and prints basic information.
with MongoClient('mongodb://localhost:27017/') as client:
MongoClient takes a connection string. Without arguments, it
connects to localhost on port 27017, so
MongoClient() is equivalent. The client manages a pool of
connections and is meant to be created once and shared by the whole
program. Used as a context manager, it closes the connections at the end
of the block.
print(client.admin.command('ping')['ok'])
The command method runs a database command. The
ping command checks that the server responds.
info = client.server_info() print(info['version'])
server_info returns information about the server, including
its version.
$ python connect.py
4.20.0
1.0
('localhost', 27017)
8.3.17
Connection errors
Creating a MongoClient does not fail when the server is not
available. The client connects in the background, and an operation waits
for a suitable server for up to serverSelectionTimeoutMS
milliseconds, 30 seconds by default.
from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError
client = MongoClient('mongodb://localhost:27018/', serverSelectionTimeoutMS=2000)
print('client created')
try:
client.admin.command('ping')
except ServerSelectionTimeoutError as e:
print(type(e).__name__)
print(str(e).split(' (configured')[0])
finally:
client.close()
Nothing listens on port 27018. The client is created without error; the
ping command raises ServerSelectionTimeoutError
after two seconds.
$ python server_timeout.py client created ServerSelectionTimeoutError localhost:27018: [Errno 111] Connection refused
Inserting documents
In the following example, we create a collection with eight documents.
from pymongo import MongoClient
cars = [
{'name': 'Audi', 'price': 52642},
{'name': 'Mercedes', 'price': 57127},
{'name': 'Skoda', 'price': 9000},
{'name': 'Volvo', 'price': 29000},
{'name': 'Bentley', 'price': 350000},
{'name': 'Citroen', 'price': 21000},
{'name': 'Hummer', 'price': 41400},
{'name': 'Volkswagen', 'price': 21600},
]
with MongoClient() as client:
db = client.testdb
print(client.list_database_names())
result = db.cars.insert_many(cars)
print(len(result.inserted_ids))
print(result.inserted_ids[0])
print(client.list_database_names())
print(db.list_collection_names())
Databases and collections are created lazily. client.testdb
and db.cars are only references; the database and the
collection come into existence with the first inserted document.
result = db.cars.insert_many(cars) print(len(result.inserted_ids)) print(result.inserted_ids[0])
insert_many inserts a list of documents and returns an
InsertManyResult. Since the documents do not have an
_id field, which serves as the primary key, PyMongo generates
an ObjectId for each of them.
print(client.list_database_names()) print(db.list_collection_names())
list_database_names and list_collection_names
return the names of databases and collections. Before the insert,
testdb does not exist. Older PyMongo versions had the
collection_names method; it was removed in PyMongo 4.
$ python create_collection.py ['admin', 'config', 'local'] 8 6afcc7974fd4f62db3e1b4c0 ['admin', 'config', 'local', 'testdb'] ['cars']
Checking data with mongosh
We can verify the data with the mongosh shell.
$ docker exec mongo mongosh --quiet testdb --eval 'db.cars.find().limit(3)'
[
{
_id: ObjectId('6afcc7974fd4f62db3e1b4c0'),
name: 'Audi',
price: 52642
},
{
_id: ObjectId('6afcc7974fd4f62db3e1b4c1'),
name: 'Mercedes',
price: 57127
},
{
_id: ObjectId('6afcc7974fd4f62db3e1b4c2'),
name: 'Skoda',
price: 9000
}
]
Inserting a single document
A single document is inserted with insert_one.
from pymongo import MongoClient
with MongoClient() as client:
db = client.testdb
car = {'name': 'Tesla', 'price': 45000}
result = db.cars.insert_one(car)
print(result.acknowledged)
print(result.inserted_id)
print(car)
insert_one returns an InsertOneResult with the
id of the new document. PyMongo adds the generated _id to the
dictionary that we passed in.
$ python insert_one.py
True
6afcc79859dc957ea100b0ad
{'name': 'Tesla', 'price': 45000, '_id': ObjectId('6afcc79859dc957ea100b0ad')}
ObjectId
An ObjectId is a 12-byte value. Its first four bytes contain
the creation time in seconds, so the ids sort roughly in the order in
which they were created.
from bson import ObjectId
from pymongo import MongoClient
with MongoClient() as client:
car = client.testdb.cars.find_one({'name': 'Tesla'})
oid = car['_id']
print(type(oid))
print(str(oid), len(str(oid)))
print(oid.generation_time)
print(client.testdb.cars.find_one({'_id': ObjectId(str(oid))}))
print(ObjectId.is_valid('Tesla'))
The string form of an ObjectId has 24 hexadecimal digits.
generation_time returns the time encoded in the id as an
aware datetime in UTC. A string is not equal to an
ObjectId; to find a document by an id that comes as text, for
example from a URL, we convert it with ObjectId first.
is_valid checks whether a string can be converted.
$ python object_id.py
<class 'bson.objectid.ObjectId'>
6afcc79859dc957ea100b0ad 24
2026-11-17 21:31:04+00:00
{'_id': ObjectId('6afcc79859dc957ea100b0ad'), 'name': 'Tesla', 'price': 45000}
False
Dropping a collection
The drop method removes a collection with all its documents
and indexes.
from pymongo import MongoClient
with MongoClient() as client:
db = client.testdb
db.temp.insert_one({'x': 1})
print(db.list_collection_names())
db.temp.drop()
print(db.list_collection_names())
The example creates a temp collection with one document and
drops it.
$ python drop_collection.py ['cars', 'temp'] ['cars']
Running commands
The command method runs a database command and returns the
reply as a dictionary.
from pymongo import MongoClient
with MongoClient() as client:
status = client.admin.command('serverStatus')
print(status['version'], status['process'])
print(status['connections']['current'] > 0)
print(status['storageEngine']['name'])
stats = client.testdb.command('dbStats')
print(stats['db'], stats['collections'], stats['objects'])
print(client.testdb.command('count', 'cars')['n'])
The serverStatus command returns a large document about the
state of the server; we print a few fields. dbStats returns
statistics about a database. The count command takes the
collection name as its value.
$ python commands.py 8.3.17 mongod True wiredTiger testdb 1 9 9
Cursors
The find method returns a cursor, a reference to the result
set of a query. The cursor fetches documents from the server in batches
as we iterate over it. The server closes cursors that are inactive for ten
minutes.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars.find({}, {'_id': 0})
print(type(cars))
print(next(cars))
print(next(cars))
cars.rewind()
print(next(cars))
rest = cars.to_list()
print(len(rest))
print(cars.alive)
The second argument of find is a projection; here it
excludes the _id field. The built-in next
function returns the next document. rewind resets the cursor
so that the query runs again from the start. to_list reads
all remaining documents into a list; after that, the cursor is exhausted
and its alive property is False.
$ python cursor.py
<class 'pymongo.synchronous.cursor.Cursor'>
{'name': 'Audi', 'price': 52642}
{'name': 'Mercedes', 'price': 57127}
{'name': 'Audi', 'price': 52642}
8
False
Reading all documents
The usual way to read documents is to iterate over the cursor with a
for loop.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars.find()
for car in cars:
print(f"{car['name']} {car['price']}")
find without arguments matches all documents of the
collection. Without a sort, the server returns them in no guaranteed
order; for a small collection that has only seen inserts, it is usually
the insertion order.
$ python all_cars.py Audi 52642 Mercedes 57127 Skoda 9000 Volvo 29000 Bentley 350000 Citroen 21000 Hummer 41400 Volkswagen 21600 Tesla 45000
Finding a single document
The find_one method returns the first matching document or
None.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars
print(cars.find_one({'name': 'Volvo'}, {'_id': 0}))
print(cars.find_one({'price': {'$gt': 100000}}, {'_id': 0}))
print(cars.find_one({'name': 'Lada'}))
The first argument of find_one is a filter, the second a
projection.
$ python find_one.py
{'name': 'Volvo', 'price': 29000}
{'name': 'Bentley', 'price': 350000}
None
Counting documents
The count_documents method counts the documents that match a
filter.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars
print(cars.count_documents({}))
print(cars.count_documents({'price': {'$gt': 50000}}))
print(cars.estimated_document_count())
try:
cars.find().count()
except AttributeError as e:
print(e)
count_documents runs an aggregation over the matching
documents. estimated_document_count takes the count from the
collection metadata; it is faster but cannot take a filter. The
count method of the cursor was removed in PyMongo 4.
$ python count_cars.py 9 3 9 'Cursor' object has no attribute 'count'
Filters
A filter is a document that the returned documents must match. Fields are
compared for equality; operators starting with $ express
other conditions.
from pymongo import MongoClient
def names(query):
return [car['name'] for car in client.testdb.cars.find(query)]
with MongoClient() as client:
print(names({'price': {'$gt': 50000}}))
print(names({'price': {'$gte': 21000, '$lte': 30000}}))
print(names({'name': {'$in': ['Audi', 'Skoda', 'Lada']}}))
print(names({'$or': [{'price': {'$lt': 10000}}, {'price': {'$gt': 100000}}]}))
print(names({'name': {'$regex': '^V'}}))
print(names({'name': {'$regex': 'er', '$options': 'i'}}))
print(names({'name': {'$not': {'$regex': 'e'}}}))
$gt, $gte, $lt, and
$lte compare values. Several conditions on the same field are
combined in one document. $in matches any value from a list.
$or takes a list of filters. $regex matches a
regular expression; the i option makes it case-insensitive.
$not negates a condition, so the last query returns cars
without the letter e in the name.
$ python filtering.py ['Audi', 'Mercedes', 'Bentley'] ['Volvo', 'Citroen', 'Volkswagen'] ['Audi', 'Skoda'] ['Skoda', 'Bentley'] ['Volvo', 'Volkswagen'] ['Mercedes', 'Hummer'] ['Audi', 'Skoda', 'Volvo']
Projections
A projection selects the fields of the returned documents. It is the
second argument of find and find_one.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars
for car in cars.find({}, {'name': 1}).limit(2):
print(car)
for car in cars.find({}, {'_id': 0, 'name': 1}).limit(2):
print(car)
for car in cars.find({}, {'_id': 0, 'price': 0}).limit(2):
print(car)
for car in cars.find({}, ['name', 'price']).limit(2):
print(car)
A value of 1 includes a field, 0 excludes it. The _id field is
included unless it is excluded explicitly. Apart from _id, a
projection cannot mix inclusion and exclusion. A list of field names is a
shorthand for an inclusion projection.
$ python projection.py
{'_id': ObjectId('6afcc7974fd4f62db3e1b4c0'), 'name': 'Audi'}
{'_id': ObjectId('6afcc7974fd4f62db3e1b4c1'), 'name': 'Mercedes'}
{'name': 'Audi'}
{'name': 'Mercedes'}
{'name': 'Audi'}
{'name': 'Mercedes'}
{'_id': ObjectId('6afcc7974fd4f62db3e1b4c0'), 'name': 'Audi', 'price': 52642}
{'_id': ObjectId('6afcc7974fd4f62db3e1b4c1'), 'name': 'Mercedes', 'price': 57127}
Sorting documents
The sort method of the cursor sets the order of the
documents.
from pymongo import MongoClient, ASCENDING, DESCENDING
with MongoClient() as client:
cars = client.testdb.cars
for car in cars.find().sort('price', DESCENDING).limit(3):
print(car['name'], car['price'])
print('----------')
query = cars.find({}, {'_id': 0}).sort([('price', ASCENDING), ('name', ASCENDING)])
for car in query.limit(3):
print(car)
sort takes a field name and a direction, or a list of
(field, direction) pairs for several keys. The ASCENDING and
DESCENDING constants are 1 and -1.
$ python sorting.py
Bentley 350000
Mercedes 57127
Audi 52642
----------
{'name': 'Skoda', 'price': 9000}
{'name': 'Citroen', 'price': 21000}
{'name': 'Volkswagen', 'price': 21600}
Skipping and limiting
The skip method skips documents and limit
limits their number.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars.find().sort('_id').skip(2).limit(3)
for car in cars:
print(f"{car['name']}: {car['price']}")
The example skips the first two documents and returns the next three.
For a stable result, we sort by _id. Cursor methods return
the cursor, so they can be chained; the query is sent when we start
iterating.
$ python limit_documents.py Skoda: 9000 Volvo: 29000 Bentley: 350000
Updating documents
The update_one and update_many methods modify
the documents that match a filter.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars
result = cars.update_one({'name': 'Tesla'}, {'$set': {'price': 43900}})
print(result.matched_count, result.modified_count)
result = cars.update_one({'name': 'Tesla'}, {'$set': {'price': 43900}})
print(result.matched_count, result.modified_count)
result = cars.update_many({'price': {'$lt': 30000}}, {'$inc': {'price': 1000}})
print(result.matched_count, result.modified_count)
result = cars.update_many({}, {'$set': {'currency': 'EUR'}})
print(result.modified_count)
print(cars.find_one({'name': 'Skoda'}, {'_id': 0}))
The second argument is an update document with operators such as
$set, which sets a field, and $inc, which
increments it. The result has matched_count and
modified_count. The second update of Tesla matches the
document but does not modify it, because the price is already 43900.
$set also adds fields that do not exist; every car now has
a currency field.
$ python update_documents.py
1 1
1 0
4 4
9
{'name': 'Skoda', 'price': 10000, 'currency': 'EUR'}
Upserts
With upsert=True, an update inserts a new document if no
document matches the filter.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars
result = cars.update_one({'name': 'Lada'},
{'$set': {'price': 8000, 'currency': 'EUR'}},
upsert=True)
print(result.matched_count, result.upserted_id)
result = cars.update_one({'name': 'Lada'},
{'$set': {'price': 8500, 'currency': 'EUR'}},
upsert=True)
print(result.matched_count, result.upserted_id)
print(cars.find_one({'name': 'Lada'}, {'_id': 0}))
The first call does not find Lada and inserts it; the new document
contains the fields of the filter and of $set.
upserted_id holds its id. The second call finds the
document and updates it.
$ python upsert.py
0 6afcc7a0532afd2ad6a19b86
1 None
{'name': 'Lada', 'currency': 'EUR', 'price': 8500}
Find and update
The find_one_and_update method updates a document and
returns it in one atomic operation.
from pymongo import MongoClient, ReturnDocument
with MongoClient() as client:
cars = client.testdb.cars
before = cars.find_one_and_update({'name': 'Volvo'}, {'$inc': {'price': 500}},
projection={'_id': 0})
print(before)
after = cars.find_one_and_update({'name': 'Volvo'}, {'$inc': {'price': 500}},
projection={'_id': 0},
return_document=ReturnDocument.AFTER)
print(after)
By default, the method returns the document as it was before the update.
With ReturnDocument.AFTER, it returns the updated
document. This is useful for counters and queues, where we need the value
that our update produced.
$ python find_and_update.py
{'name': 'Volvo', 'price': 30000, 'currency': 'EUR'}
{'name': 'Volvo', 'price': 31000, 'currency': 'EUR'}
Replacing a document
The replace_one method replaces a whole document.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars
print(cars.find_one({'name': 'Hummer'}))
cars.replace_one({'name': 'Hummer'}, {'name': 'Hummer EV', 'price': 98845})
print(cars.find_one({'name': {'$regex': '^Hummer'}}))
The replacement keeps the _id but contains no other fields
of the original document; the currency field is gone. Unlike
update_one, the replacement must not contain update
operators.
$ python replace_one.py
{'_id': ObjectId('6afcc7974fd4f62db3e1b4c6'), 'name': 'Hummer', 'price': 41400, 'currency': 'EUR'}
{'_id': ObjectId('6afcc7974fd4f62db3e1b4c6'), 'name': 'Hummer EV', 'price': 98845}
Deleting documents
Documents are removed with delete_one and
delete_many.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars
result = cars.delete_one({'name': 'Tesla'})
print(result.deleted_count)
result = cars.delete_many({'price': {'$lt': 10000}})
print(result.deleted_count)
print(cars.count_documents({}))
The example deletes Tesla and all cars cheaper than 10000, which is only
Lada. deleted_count holds the number of deleted documents.
$ python delete_documents.py 1 1 8
Bulk writes
The bulk_write method sends several write operations to the
server in one request.
from pymongo import MongoClient, InsertOne, UpdateOne, DeleteOne
with MongoClient() as client:
cars = client.testdb.cars
requests = [
InsertOne({'name': 'Ford', 'price': 27300, 'currency': 'EUR'}),
InsertOne({'name': 'Toyota', 'price': 31500, 'currency': 'EUR'}),
UpdateOne({'name': 'Ford'}, {'$set': {'price': 26900}}),
DeleteOne({'name': 'Toyota'}),
]
result = cars.bulk_write(requests)
print(result.inserted_count, result.modified_count, result.deleted_count)
print(cars.find_one({'name': 'Ford'}, {'_id': 0}))
The operations are given as InsertOne,
UpdateOne, UpdateMany, ReplaceOne,
DeleteOne, and DeleteMany objects. By default,
the operations are ordered: they run in sequence and the server stops at
the first error. With ordered=False, the server may run them
in any order and continues after errors.
$ python bulk_write.py
2 1 1
{'name': 'Ford', 'price': 26900, 'currency': 'EUR'}
Embedded documents and arrays
Documents can contain other documents and arrays. In this and the next
examples, we use a library database with authors and
books.
from pymongo import MongoClient
authors = [
{'_id': 'austen', 'name': 'Jane Austen', 'born': 1775},
{'_id': 'tolstoy', 'name': 'Leo Tolstoy', 'born': 1828},
{'_id': 'kafka', 'name': 'Franz Kafka', 'born': 1883},
]
books = [
{'title': 'Pride and Prejudice', 'author': 'austen', 'year': 1813,
'genres': ['novel', 'romance'], 'details': {'pages': 432, 'language': 'English'}},
{'title': 'Emma', 'author': 'austen', 'year': 1815,
'genres': ['novel', 'romance', 'comedy'], 'details': {'pages': 474, 'language': 'English'}},
{'title': 'War and Peace', 'author': 'tolstoy', 'year': 1869,
'genres': ['novel', 'historical'], 'details': {'pages': 1225, 'language': 'Russian'}},
{'title': 'Anna Karenina', 'author': 'tolstoy', 'year': 1878,
'genres': ['novel', 'romance'], 'details': {'pages': 864, 'language': 'Russian'}},
{'title': 'The Trial', 'author': 'kafka', 'year': 1925,
'genres': ['novel', 'absurdist'], 'details': {'pages': 255, 'language': 'German'}},
{'title': 'The Metamorphosis', 'author': 'kafka', 'year': 1915,
'genres': ['novella', 'absurdist'], 'details': {'pages': 70, 'language': 'German'}},
]
with MongoClient() as client:
db = client.library
db.authors.drop()
db.books.drop()
db.authors.insert_many(authors)
db.books.insert_many(books)
print(db.authors.count_documents({}), db.books.count_documents({}))
The authors have readable string ids. Each book refers to its author by
id, has an array of genres and an embedded details
document.
$ python books.py 3 6
Querying embedded documents and arrays
Fields of embedded documents are accessed with dot notation.
from pymongo import MongoClient
def titles(query):
return [b['title'] for b in client.library.books.find(query).sort('year')]
with MongoClient() as client:
print(titles({'details.language': 'Russian'}))
print(titles({'details.pages': {'$gt': 800}}))
print(titles({'genres': 'romance'}))
print(titles({'genres': {'$all': ['novel', 'absurdist']}}))
print(titles({'genres': {'$size': 3}}))
print(titles({'genres.0': 'novella'}))
details.language refers to the language field of
the embedded document; the field name must be quoted. A filter that
compares an array field with a single value matches documents whose array
contains the value. $all requires all listed values,
$size matches the length of the array, and a numeric index
such as genres.0 refers to an element.
$ python nested.py ['War and Peace', 'Anna Karenina'] ['War and Peace', 'Anna Karenina'] ['Pride and Prejudice', 'Emma', 'Anna Karenina'] ['The Trial'] ['Emma'] ['The Metamorphosis']
Updating arrays
Update operators can modify arrays and embedded documents.
from pymongo import MongoClient
with MongoClient() as client:
books = client.library.books
query = {'title': 'Emma'}
books.update_one(query, {'$push': {'genres': 'satire'}})
print(books.find_one(query)['genres'])
books.update_one(query, {'$addToSet': {'genres': 'novel'}})
print(books.find_one(query)['genres'])
books.update_one(query, {'$pull': {'genres': {'$in': ['comedy', 'satire']}}})
print(books.find_one(query)['genres'])
books.update_one(query, {'$set': {'details.pages': 480}, '$unset': {'details.language': ''}})
print(books.find_one(query)['details'])
$push appends a value to an array. $addToSet
appends it only if it is not present yet; novel is already
there, so the array does not change. $pull removes the
elements that match a condition. $set with dot notation
changes a field of the embedded document and $unset removes
a field.
$ python update_arrays.py
['novel', 'romance', 'comedy', 'satire']
['novel', 'romance', 'comedy', 'satire']
['novel', 'romance']
{'pages': 480}
Aggregation
The aggregate method runs an aggregation pipeline, a list of
stages that transform the documents one after another.
from pymongo import MongoClient
with MongoClient() as client:
cars = client.testdb.cars
pipeline = [
{'$group': {'_id': None, 'total': {'$sum': '$price'},
'average': {'$avg': '$price'}, 'count': {'$sum': 1}}}
]
result = cars.aggregate(pipeline).next()
print(result)
pipeline = [
{'$match': {'name': {'$in': ['Audi', 'Volvo']}}},
{'$group': {'_id': None, 'total': {'$sum': '$price'}}},
]
print(cars.aggregate(pipeline).next()['total'])
The $group stage groups documents by the _id
expression; None puts all documents into one group. The
accumulators $sum and $avg compute values for
each group; {'$sum': 1} counts the documents. A string
starting with $, such as '$price', refers to a
field. In the second pipeline, the $match stage first selects
Audi and Volvo.
$ python aggregate_sum.py
{'_id': None, 'total': 671114, 'average': 74568.22222222222, 'count': 9}
83642
Grouping
In the following example, we group the books by author and by genre.
from pymongo import MongoClient
with MongoClient() as client:
books = client.library.books
pipeline = [
{'$group': {'_id': '$author', 'books': {'$sum': 1},
'pages': {'$sum': '$details.pages'},
'first': {'$min': '$year'}}},
{'$sort': {'pages': -1}},
]
for row in books.aggregate(pipeline):
print(row)
pipeline = [
{'$unwind': '$genres'},
{'$group': {'_id': '$genres', 'count': {'$sum': 1}}},
{'$match': {'count': {'$gt': 1}}},
{'$sort': {'count': -1, '_id': 1}},
]
for row in books.aggregate(pipeline):
print(row['_id'], row['count'])
The first pipeline computes the number of books, the total pages, and
the year of the first book for each author and sorts the groups by pages.
In the second pipeline, $unwind creates a document for each
element of the genres array, so we can count the genres. A
$match stage after $group works like
HAVING in SQL.
$ python aggregate_group.py
{'_id': 'tolstoy', 'books': 2, 'pages': 2089, 'first': 1869}
{'_id': 'austen', 'books': 2, 'pages': 912, 'first': 1813}
{'_id': 'kafka', 'books': 2, 'pages': 325, 'first': 1915}
novel 5
romance 3
absurdist 2
Joining collections with $lookup
The $lookup stage joins documents from another collection.
from pymongo import MongoClient
with MongoClient() as client:
pipeline = [
{'$match': {'year': {'$lt': 1900}}},
{'$lookup': {'from': 'authors', 'localField': 'author',
'foreignField': '_id', 'as': 'writer'}},
{'$unwind': '$writer'},
{'$project': {'_id': 0, 'title': 1, 'year': 1,
'author': '$writer.name',
'age': {'$subtract': ['$year', '$writer.born']}}},
{'$sort': {'year': 1}},
]
for row in client.library.books.aggregate(pipeline):
print(row)
For each book, $lookup finds the authors whose
_id equals the book's author field and stores
them in the writer array. $unwind turns the
one-element array into an embedded document. $project
shapes the output and computes the age of the author when the book was
published.
$ python lookup.py
{'title': 'Pride and Prejudice', 'year': 1813, 'author': 'Jane Austen', 'age': 38}
{'title': 'Emma', 'year': 1815, 'author': 'Jane Austen', 'age': 40}
{'title': 'War and Peace', 'year': 1869, 'author': 'Leo Tolstoy', 'age': 41}
{'title': 'Anna Karenina', 'year': 1878, 'author': 'Leo Tolstoy', 'age': 50}
Indexes
Without an index, the server has to scan the whole collection to find
matching documents. The create_index method creates an
index.
from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError
with MongoClient() as client:
books = client.library.books
plan = books.find({'title': 'Emma'}).explain()['queryPlanner']['winningPlan']
print(plan['stage'])
name = books.create_index('title', unique=True)
print(name)
plan = books.find({'title': 'Emma'}).explain()['queryPlanner']['winningPlan']
print(plan['stage'], plan['indexName'])
print(list(books.index_information()))
try:
books.insert_one({'title': 'Emma', 'author': 'austen'})
except DuplicateKeyError as e:
print(e.code, e.details['errmsg'])
The explain method of the cursor shows how the server runs
the query. Before the index exists, the plan is COLLSCAN, a
collection scan. With the index, MongoDB 8 uses
EXPRESS_IXSCAN, a fast path for equality matches on a unique
index. create_index returns the name of the index, which is
made of the field name and the direction. The unique option
rejects duplicates with DuplicateKeyError, error code
11000.
$ python indexes.py
COLLSCAN
title_1
EXPRESS_IXSCAN title_1
['_id_', 'title_1']
11000 E11000 duplicate key error collection: library.books index: title_1 dup key: { title: "Emma" }
Schema validation
Collections do not require a fixed structure, but we can add a validator that the server checks on every insert and update.
from pymongo import MongoClient
from pymongo.errors import WriteError
schema = {
'$jsonSchema': {
'bsonType': 'object',
'required': ['name', 'email'],
'properties': {
'name': {'bsonType': 'string'},
'email': {'bsonType': 'string', 'pattern': '@'},
'age': {'bsonType': 'int', 'minimum': 18},
},
}
}
with MongoClient() as client:
db = client.testdb
db.drop_collection('users')
users = db.create_collection('users', validator=schema)
users.insert_one({'name': 'Jan', 'email': 'jan@example.com', 'age': 42})
try:
users.insert_one({'name': 'Paul', 'age': 12})
except WriteError as e:
print(e.code, e.details['errmsg'])
for rule in e.details['errInfo']['details']['schemaRulesNotSatisfied']:
print(rule)
print(users.count_documents({}))
The validator is a $jsonSchema document passed to
create_collection. It requires the name and
email fields and restricts their types; age
must be an integer of at least 18. A document that does not match raises
WriteError with code 121. The errInfo details
list each rule that failed.
$ python validation.py
121 Document failed validation
{'operatorName': 'properties', 'propertiesNotSatisfied': [{'propertyName': 'age', 'details': [{'operatorName': 'minimum', 'specifiedAs': {'minimum': 18}, 'reason': 'comparison failed', 'consideredValue': 12}]}]}
{'operatorName': 'required', 'specifiedAs': {'required': ['name', 'email']}, 'missingProperties': ['email']}
1
BSON types
PyMongo converts Python values to BSON types and back.
import datetime
import decimal
from bson import Decimal128
from bson.codec_options import CodecOptions
from bson.errors import InvalidDocument
from pymongo import MongoClient
with MongoClient() as client:
things = client.testdb.things
things.drop()
when = datetime.datetime(2026, 11, 17, 10, 30, 15, 123456,
tzinfo=datetime.timezone.utc)
things.insert_one({'when': when, 'price': Decimal128('19.99'),
'ratio': 0.1, 'big': 2**40, 'data': b'\x00\x01',
'tags': ['a', 'b'], 'size': {'w': 2, 'h': 3}, 'note': None})
for key, value in things.find_one({}, {'_id': 0}).items():
print(f'{key:6} {value!r}')
aware = things.with_options(codec_options=CodecOptions(tz_aware=True))
print(aware.find_one()['when'])
print(things.find_one()['price'].to_decimal())
try:
things.insert_one({'price': decimal.Decimal('19.99')})
except InvalidDocument as e:
print(e)
Strings, integers, floats, bytes, lists, dictionaries, and
None come back unchanged. A BSON date has millisecond
precision, so the microseconds are truncated. Dates are stored in UTC and
returned as naive datetime objects; with the
tz_aware codec option, they are aware objects in UTC.
decimal.Decimal cannot be encoded; decimal numbers are stored
as Decimal128, which has a to_decimal
method.
$ python bson_types.py
when datetime.datetime(2026, 11, 17, 10, 30, 15, 123000)
price Decimal128('19.99')
ratio 0.1
big 1099511627776
data b'\x00\x01'
tags ['a', 'b']
size {'w': 2, 'h': 3}
note None
2026-11-17 10:30:15.123000+00:00
19.99
Invalid document: cannot encode object: Decimal('19.99'), of type: <class 'decimal.Decimal'>
Transactions
Operations on a single document are atomic. To change several documents together, we use a transaction. Transactions require a replica set or a sharded cluster.
from pymongo import MongoClient
def transfer(session, src, dst, amount):
accounts = session.client.testdb.accounts
accounts.update_one({'_id': src}, {'$inc': {'balance': -amount}}, session=session)
balance = accounts.find_one({'_id': src}, session=session)['balance']
if balance < 0:
raise ValueError(f'insufficient funds: {balance + amount}')
accounts.update_one({'_id': dst}, {'$inc': {'balance': amount}}, session=session)
with MongoClient() as client:
accounts = client.testdb.accounts
accounts.drop()
accounts.insert_many([{'_id': 'alice', 'balance': 100},
{'_id': 'bob', 'balance': 50}])
with client.start_session() as session:
session.with_transaction(lambda s: transfer(s, 'alice', 'bob', 30))
print(list(accounts.find()))
try:
session.with_transaction(lambda s: transfer(s, 'alice', 'bob', 300))
except ValueError as e:
print('aborted:', e)
print(list(accounts.find()))
A transaction runs in a session, which we get from
start_session. The with_transaction method
starts a transaction, calls the callback with the session, and commits.
If the callback raises an exception, the transaction is aborted and the
exception propagates. It also retries the transaction on transient
errors. Every operation in the callback must get the
session argument; otherwise it runs outside the
transaction.
The second transfer withdraws the money from Alice and then finds that her balance is negative. The exception aborts the transaction, so the withdrawal is undone and both balances are unchanged.
$ python transaction.py
[{'_id': 'alice', 'balance': 70}, {'_id': 'bob', 'balance': 80}]
aborted: insufficient funds: 70
[{'_id': 'alice', 'balance': 70}, {'_id': 'bob', 'balance': 80}]
Change streams
A change stream reports the changes in a collection, a database, or the whole deployment as they happen. Like transactions, it requires a replica set.
import threading
import time
from pymongo import MongoClient
def producer():
time.sleep(0.5)
with MongoClient() as client:
events = client.testdb.events
events.insert_one({'_id': 1, 'msg': 'hello'})
events.update_one({'_id': 1}, {'$set': {'msg': 'bye'}})
events.delete_one({'_id': 1})
with MongoClient() as client:
events = client.testdb.events
events.drop()
threading.Thread(target=producer).start()
with events.watch() as stream:
for n, change in enumerate(stream, 1):
op = change['operationType']
key = change['documentKey']
if op == 'insert':
print(op, key, change['fullDocument'])
elif op == 'update':
print(op, key, change['updateDescription']['updatedFields'])
else:
print(op, key)
if n == 3:
break
The watch method opens the stream; iterating over it blocks
until the next change arrives. A thread with its own client inserts,
updates, and deletes a document. Each change event contains the type of
operation and the key of the document. An insert event carries the whole
document, an update event only the changed fields. We stop after three
events.
$ python change_stream.py
insert {'_id': 1} {'_id': 1, 'msg': 'hello'}
update {'_id': 1} {'msg': 'bye'}
delete {'_id': 1}
Asynchronous client
AsyncMongoClient is the native asyncio API of PyMongo. It
replaces the separate Motor driver, which is deprecated.
import asyncio
from pymongo import AsyncMongoClient
async def main():
async with AsyncMongoClient() as client:
cars = client.testdb.cars
car = await cars.find_one({'name': 'Audi'}, {'_id': 0})
print(car)
async for car in cars.find({'price': {'$gt': 50000}}, {'_id': 0}).sort('price'):
print(car['name'], car['price'])
counts = await asyncio.gather(
cars.count_documents({}),
client.library.books.count_documents({}),
client.library.authors.count_documents({}),
)
print(counts)
asyncio.run(main())
The asynchronous API has the same methods as the synchronous one;
operations that talk to the server are awaited. Cursors are iterated with
async for. With asyncio.gather, we run three
counts concurrently.
$ python async_client.py
{'name': 'Audi', 'price': 52642, 'currency': 'EUR'}
Audi 52642
Mercedes 57127
Hummer EV 98845
Bentley 350000
[9, 6, 3]
Source
In this article we have worked with MongoDB in Python using PyMongo. See also Python pyDAL, Python psycopg 3, Python SQLite, and Python PyMySQL.
Author
List all Python tutorials.