Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/ /

Network Compression

On this page

  • Specify Compression Algorithms
  • Compression Algorithm Dependencies

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:

  1. Snappy: available in MongoDB 3.4 and later.

  2. Zlib: available in MongoDB 3.6 and later.

  3. 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.

You can enable compression on your connection by specifying the algorithms in the following ways:

  • Adding the compressors parameter to your ConnectionString instance

  • Calling the compressorList() method from the MongoClientSettings 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 compression

  • createZlibCompressor() for Zlib compression

  • createZstdCompressor() 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)

The JDK supports Zlib compression natively, but Snappy and Zstandard depend on open source implementations. See snappy-java and zstd-java for details.

Back

MongoClient Settings