Docs Menu
Docs Home
/ / /
C++ Driver
/

Compress Network Traffic

On this page

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

The C++ driver provides a connection option to compress messages, which reduces the amount of data passed over the network between MongoDB and your application.

The C++ driver supports the following compression algorithms:

  1. Snappy: Available in MongoDB 3.6 and later.

  2. Zlib: Available in MongoDB 3.6 and later.

  3. Zstandard: Available in MongoDB 4.2 and later.

If you don't specify a compression algorithm, the driver 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, include the compressors connection option in your URI and specify the compression algorithms you want to use. The following code shows how to specify the snappy, zstd, and zlib algorithms, in that order:

#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/client.hpp>
int main()
{
mongocxx::instance instance;
mongocxx::uri uri("mongodb://<hostname>:<port>/?compressors=snappy,zstd,zlib");
mongocxx::client 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 code example specifies the zlib compression algorithm and a value of 1 for the zlibCompressionLevel option:

#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/client.hpp>
int main()
{
mongocxx::instance instance;
mongocxx::uri uri("mongodb://<hostname>:<port>/?compressors=zlib&zlibCompressionLevel=1");
mongocxx::client client(uri);
}

To learn more about the types and options used on this page, see the following API documentation:

  • mongocxx::instance

  • mongocxx::client

  • mongocxx::uri

  • Compression Options

Back

Configure Transport Layer Security (TLS)