Compress Network Traffic
Overview
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:
Snappy: Available in MongoDB 3.6 and later.
Zlib: Available in MongoDB 3.6 and later.
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.
Specify Compression Algorithms
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:
int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://<hostname>:<port>/?compressors=snappy,zstd,zlib"); mongocxx::client client(uri); }
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:
int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://<hostname>:<port>/?compressors=zlib&zlibCompressionLevel=1"); mongocxx::client client(uri); }
API Documentation
To learn more about the types and options used on this page, see the following API documentation: