Docs Menu
Docs Home
/
PHP Library Manual
/ /

Compress Network Traffic

In this guide, you can learn how to configure network compression for your connection to MongoDB.

Network compression is a feature that allows you to compress and decompress messages sent between your application and MongoDB, reducing the total amount of data passed over the network.

The PHP library supports the following compressors:

  1. Snappy

  2. Zlib

  3. Zstandard

Note

Compressor Selection

If you specify multiple compressors to use on your connection, the driver selects the first one that is supported by the MongoDB deployment that the PHP library is connected to.

To enable compression for the connection to your MongoDB deployment, 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 MongoDB\Client constructor.

  • Specify the algorithms in your connection string.

The following example shows how to specify Snappy, Zlib, and Zstandard as the compressors for a connection. Select the MongoDB\Client or Connection URI tab to see the corresponding code:

$client = new MongoDB\Client(
'mongodb://<hostname>:<port>',
['compressors' => 'snappy,zstd,zlib'],
);
$uri = 'mongodb://<hostname>:<port>/?compressors=snappy,zstd,zlib';
$client = new MongoDB\Client($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 example specifies the zlib compression algorithm and a zlibCompressionLevel value of 1. Select the MongoDB\Client or Connection URI tab to see the corresponding code:

$uriOptions = [
'compressors' => 'zlib',
'zlibCompressionLevel' => 1,
];
$client = new MongoDB\Client(
'mongodb://<hostname>:<port>',
$uriOptions,
);
$uri = 'mongodb://<hostname>:<port>/?compressors=zlib&zlibCompressionLevel=1';
$client = new MongoDB\Client($uri);

To learn more about the MongoDB\Client class, see MongoDB\Client in the library API documentation.

To view a full list of URI options that you can pass to a MongoDB\Client, see the MongoDB\Driver\Manager::__construct parameters in the extension API documentation.

Back

Stable API

On this page