Version Compatibility
All versions of the Kotlin Sync driver support Snappy, Zlib, and Zstandard compression.
The following table lists the minimum supported MongoDB Server version for each algorithm:
Enable Network Compression
To enable network compression for your MongoDB connection, install the required dependencies and specify the compression algorithms that you want to use.
Install Dependencies
The following table lists each algorithm and the dependency it requires, if any:
Compression Algorithm | Dependency |
|---|---|
Snappy | Download |
Zlib | None. The driver natively supports Zlib compression. |
Zstandard | Download |
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
compressorsparameter 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)
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: