Docs Home → Develop Applications → Python Drivers → PyMongo
Compress Network Traffic
Overview
PyMongo provides a connection option to compress messages, which reduces the amount of data passed over the network between MongoDB and your application.
PyMongo supports the following compression algorithms.
Snappy: Available in MongoDB 3.6 and later. This option requires the python-snappy package.
Zlib: Available in MongoDB 3.6 and later. This option requires the zlib module, included in the standard library in Python v1.5 and later.
Zstandard: Available in MongoDB 4.2 and later. This option requires the zstandard package.
If you don't specify a compression algorithm, PyMongo doesn't compress your network traffic. If you specify multiple compression algorithms, the driver selects the first one in the list supported by your MongoDB instance.
Specify Compression Algorithms
To enable compression for the connection to your MongoDB instance, use the
compressors
connection option and specify the compression algorithms you want to use.
You can do this in two ways:
Pass the algorithms as an argument to the
MongoClient
constructor.Specify the algorithms in your connection string.
The following code example shows both options:
Set the zlib Compression Level
If you specify zlib
as one of your compression algorithms, you can also use the
zlibCompressionLevel
option to specify a compression level. This option accepts
an integer value between -1
and 9
:
-1: (Default). zlib uses its default compression level (usually
6
).0: No compression.
1: Fastest speed but lowest compression.
9: Best compression but slowest speed.
The following code example specifies the zlib
compression algorithm and a value of
1
for the zlibCompressionLevel
option: