- Scala Driver
- Tutorials
- Connect to MongoDB
- Compression
Compression
The Java driver supports compression of messages to and from MongoDB servers. The driver implements the three algorithms that are supported by MongoDB servers:
- Snappy: Snappy compression can be used when connecting to MongoDB servers starting with the 3.4 release.
- Zlib: Zlib compression can be used when connecting to MongoDB servers starting with the 3.6 release.
- Zstandard: Zstandard compression can be used when connecting to MongoDB servers starting with the 4.2 release.
The driver will negotiate which, if any, compression algorithm is used based on capabilities advertised by the server in the hello command response.
Specify compression via ConnectionString
import org.mongodb.scala._
To specify compression with ConnectionString
, specify compressors
as part of the connection
string, as in:
val mongoClient: MongoClient = MongoClient("mongodb://localhost/?compressors=snappy")
for Snappy compression, or
val mongoClient: MongoClient = MongoClient("mongodb://localhost/?compressors=zlib")
for zlib compression, or
val mongoClient: MongoClient = MongoClient("mongodb://localhost/?compressors=zstd")
for Zstandard compression, or
val mongoClient: MongoClient = MongoClient("mongodb://localhost/?compressors=snappy,zlib,zstd")
to configure multiple compressors.
In all cases the driver will use the first compressor in the list for which the server advertises support.
Specify compression via MongoClientSettings
import org.mongodb.scala._
import scala.collection.JavaConverters._
To specify compression with MongoClientSettings
, set the compressors
property
to a list of MongoCompressor
instances:
val settings = MongoClientSettings.builder()
.compressorList(List(MongoCompressor.createSnappyCompressor).asJava)
.build()
val client = MongoClient(settings)
for Snappy compression, or
val settings = MongoClientSettings.builder()
.compressorList(List(MongoCompressor.createZlibCompressor).asJava)
.build()
val client = MongoClient(settings)
for zlib compression, or
val settings = MongoClientSettings.builder()
.compressorList(List(MongoCompressor.createZstdCompressor).asJava)
.build()
val client = MongoClient(settings)
for Zstandard compression, or
val settings = MongoClientSettings.builder()
.compressorList(List(MongoCompressor.createSnappyCompressor,
MongoCompressor.createZlibCompressor,
MongoCompressor.createZstdCompressor).asJava)
.build()
val client = MongoClient(settings)
to configure multiple compressors.
As with configuration with a URI, the driver will use the first compressor in the list for which the server advertises support.
Dependencies
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.