Docs Menu
Docs Home
/ / /
Java Sync
/ /

Network Compression

You can enable a driver option to compress messages which 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.2-3

If you specify multiple compression algorithms, the driver selects the first one in the list supported by the MongoDB instance to which it is connected.

Note

Applications that require Snappy or Zstandard compression must add explicit dependencies for those algorithms.

You can enable compression for the connection to your MongoDB instance by specifying the algorithms in one of two ways: adding the parameter to your connection string using ConnectionString or by calling the method in the MongoClientSettings.Builder class.

To enable compression using the ConnectionString, add the parameter compressors in the connection string passed to MongoClients.create(). You can specify one or more compression algorithms, separating them with commas:

ConnectionString connectionString = new ConnectionString("mongodb+srv://<db_username>:<db_password>@<cluster-url>/?compressors=snappy,zlib,zstd");
MongoClient mongoClient = MongoClients.create(connectionString);

Specify compression algorithms using the following strings:

To enable compression using the MongoClientSettings, pass the compressorList() builder method a list of MongoCompressor instances. You can specify one or more compression algorithms in the list:

MongoClientSettings settings = MongoClientSettings.builder()
.compressorList(Arrays.asList(MongoCompressor.createSnappyCompressor(),
MongoCompressor.createZlibCompressor(),
MongoCompressor.createZstdCompressor()))
.build();
MongoClient client = MongoClients.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

Specify MongoClient Settings