Docs Menu
Docs Home
/ / /
PyMongo
/

Compress Network Traffic

On this page

  • Overview
  • Specify Compression Algorithms
  • Set the zlib Compression Level

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.

  1. Snappy: Available in MongoDB 3.6 and later. This option requires the python-snappy package.

  2. 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.

  3. 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.

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:

client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>",
compressors = "snappy,zstd,zlib")
uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?"
"compressors=snappy,zstd,zlib")
client = pymongo.MongoClient(uri)

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:

client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>",
compressors = "zlib",
zlibCompressionLevel=1)
uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?"
"compressors=zlib"
"zlibCompressionLevel=1")
client = pymongo.MongoClient(uri)

Back

Configure TLS