Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Scala Driver
/ /

Compression

The Scala driver supports compression of messages to and from MongoDB servers. The driver implements the three algorithms that are supported by MongoDB servers:

The driver will negotiate which, if any, compression algorithm is used based on capabilities advertised by the server in the hello command response.

Include the following import statements:

import org.mongodb.scala._

To specify compression within a ConnectionString, specify compressors as part of the connection string.

The following code specifies the Snappy compression algorithm:

val mongoClient: MongoClient = MongoClient("mongodb://localhost/?compressors=snappy")

The following code specifies the Zlib compression algorithm:

val mongoClient: MongoClient = MongoClient("mongodb://localhost/?compressors=zlib")

The following code specifies the Zstandard compression algorithm:

val mongoClient: MongoClient = MongoClient("mongodb://localhost/?compressors=zstd")

The following code specifies multiple compression algorithms:

val mongoClient: MongoClient = MongoClient("mongodb://localhost/?compressors=snappy,zlib,zstd")

In all cases, the driver uses the first compressor in the list for which the server has support.

Include the following import statements:

import org.mongodb.scala._
import scala.collection.JavaConverters._

To specify compression within a MongoClientSettings instance, set the compressors property to a list of MongoCompressor instances.

The following code specifies the Snappy compression algorithm:

val settings = MongoClientSettings.builder()
.compressorList(List(MongoCompressor.createSnappyCompressor).asJava)
.build()
val client = MongoClient(settings)

The following code specifies the Zlib compression algorithm:

val settings = MongoClientSettings.builder()
.compressorList(List(MongoCompressor.createZlibCompressor).asJava)
.build()
val client = MongoClient(settings)

The following code specifies the Zstandard compression algorithm:

val settings = MongoClientSettings.builder()
.compressorList(List(MongoCompressor.createZstdCompressor).asJava)
.build()
val client = MongoClient(settings)

The following code specifies multiple compression algorithms:

val settings = MongoClientSettings.builder()
.compressorList(List(MongoCompressor.createSnappyCompressor,
MongoCompressor.createZlibCompressor,
MongoCompressor.createZstdCompressor).asJava)
.build()
val client = MongoClient(settings)

As with configuration that uses the connection string, the driver uses the first compressor in the list for which the server has support.

As the JDK has no built-in support for Snappy or Zstandard, the driver takes a dependency on existing open-source Snappy and Zstandard implementations. See the snappy-java GitHub repository and the zstd-java GitHub repository for details.

Back

Authentication

On this page