Network Compression
The MongoDB Kotlin Driver provides a connection option to compress messages, This reduces the amount of data passed over the network between MongoDB and your application.
The driver supports the following algorithms:
Snappy: available in MongoDB 3.4 and later.
Zlib: available in MongoDB 3.6 and later.
Zstandard: available in MongoDB 4.2 and later.
The driver tests against the following versions of these libraries:
org.xerial.snappy:snappy-java:1.1.8.4
com.github.luben:zstd-jni:1.5.5-2
If you specify multiple compression algorithms, the driver selects the first one that is supported by the MongoDB instance that the driver is connected to.
Note
If your application requires Snappy or Zstandard compression, you must add explicit dependencies for those algorithms.
Specify Compression Algorithms
You can enable compression on your connection by specifying the algorithms in the following ways:
Adding the
compressors
parameter to yourConnectionString
instanceCalling the
compressorList()
method from theMongoClientSettings
builder
To enable compression on your connection in a ConnectionString
instance, specify the compressors
parameter. You can specify
one or more of the following values for the compressors
parameter:
The following example shows how to specify Snappy, Zlib, and Zstandard as the compression algorithms for a connection:
// Replace the placeholders with values from your MongoDB deployment's connection string val connectionString = ConnectionString("mongodb+srv://<user>:<password>@<cluster-url>/?compressors=snappy,zlib,zstd") // Create a new client with your settings val mongoClient = MongoClient.create(connectionString)
To enable compression using within your MongoClientSettings, call the compressorList() builder method and pass one or more MongoCompressor instances as a parameter.
You can specify compression algorithms by calling the following
methods from MongoCompressor
:
createSnappyCompressor()
for Snappy compressioncreateZlibCompressor()
for Zlib compressioncreateZstdCompressor()
for Zstandard compression
The following example shows how to specify Snappy, Zlib, and Zstandard as the compression algorithms for a connection:
// Replace the placeholder with your MongoDB deployment's connection string val uri = "<connection string>" val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString(uri)) .compressorList( listOf( MongoCompressor.createSnappyCompressor(), MongoCompressor.createZlibCompressor(), MongoCompressor.createZstdCompressor()) ) .build() // Create a new client with your settings val mongoClient = MongoClient.create(settings)
Compression Algorithm Dependencies
The JDK supports Zlib compression natively, but Snappy and Zstandard depend on open source implementations. See snappy-java and zstd-java for details.