Overview
In this guide, you can learn how to use the Kotlin Sync driver to enable network compression. The driver provides a connection option to compress messages, which reduces the amount of data passed over the network between MongoDB and your application.
The driver supports the following compression algorithms:
If you specify multiple compression algorithms, the driver selects the first one in the list supported by your MongoDB instance.
Note
Applications that require Snappy or Zstandard compression must add explicit dependencies for those algorithms. To learn more, see the Compression Algorithm Dependencies section of this guide.
Specify Compression Algorithms
You can enable compression for the connection to your MongoDB instance by specifying the algorithms in one of the following ways:
Chain the
compressorList()
method to theMongoClientSettings.builder()
method.Use the
compressors
parameter in your connection URI.
The following examples demonstrate how to specify all available compressors while connecting to MongoDB. Select the MongoClientSettings or Connection URI tab to see the corresponding syntax:
val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString("<connection string>")) .compressorList( listOf( MongoCompressor.createSnappyCompressor(), MongoCompressor.createZlibCompressor(), MongoCompressor.createZstdCompressor()) ) .build() val mongoClient = MongoClient.create(settings)
val uri = ConnectionString("mongodb+srv://<db_username>:<db_password>@<cluster-url>/?compressors=snappy,zlib,zstd") val mongoClient = MongoClient.create(uri)
Specify the Zlib Compression Level
If you specify zlib
as one of your compression algorithms, you can also use the
MongoCompressor.LEVEL
property to specify a compression level. This option accepts
an integer value between -1
and 9
:
-1: Default compression (usually
6
)0: No compression
1: Fastest speed but lowest compression
9: Best compression but slowest speed
The following examples demonstrate how to specify a compression level for
the zlib
compressor. Select the MongoClientSettings or Connection URI
tab to see the corresponding syntax:
val zlib = MongoCompressor.createZlibCompressor() val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString(uri)) .compressorList(listOf(zlib.withProperty(MongoCompressor.LEVEL, <level>))) .build() val mongoClient = MongoClient.create(settings)
val uri = "mongodb://<db_username>:<db_password>@<hostname>:<port>/?" + "compressors=zlib" + "zlibCompressionLevel=<zlib compression level>" val mongoClient = MongoClient.create(uri)
Compression Algorithm Dependencies
The JDK natively supports Zlib compression. However, Snappy and Zstandard depend on open source Java implementations. To learn more about these implementations, see the following GitHub repositories:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: