ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

Compress Network Traffic

In this guide, you can learn how to use the Java driver to enable network compression. The driver provides a connection option to compress messages, which reduces the amount of data passed over the network between MongoDB and your application.

The driver supports the following compression algorithms:

  • Snappy: Available in MongoDB Server v3.4 and later.

  • Zlib: Available in MongoDB Server v3.6 and later.

  • Zstandard: Available in MongoDB Server v4.2 and later.

The driver tests against the following versions of these libraries:

  • org.xerial.snappy:snappy-java:1.1.10.3

  • com.github.luben:zstd-jni:1.5.5-3

If you specify multiple compression algorithms, the driver selects the first one in the list supported by your MongoDB instance.

Note

Applications that require Snappy or Zstandard compression must add explicit dependencies for those algorithms. To learn more, see the Compression Algorithm Dependencies section of this guide.

You can enable compression for the connection to your MongoDB instance by specifying the algorithms in one of the following ways:

  • Use the compressors parameter in your connection string.

  • Chain the compressorList() method to the MongoClientSettings.builder() method.

This example shows how to specify the Snappy, Zstandard, and Zlib compression algorithms. Select the Connection String or MongoClientSettings tab to see the corresponding syntax:

ConnectionString connectionString = new ConnectionString(
"mongodb+srv://<db_username>:<db_password>@<cluster-url>/?compressors=snappy,zlib,zstd");
MongoClient client = MongoClients.create(connectionString);
MongoClientSettings settings = MongoClientSettings.builder()
.compressorList(Arrays.asList(MongoCompressor.createSnappyCompressor(),
MongoCompressor.createZlibCompressor(),
MongoCompressor.createZstdCompressor()))
.build();
MongoClient client = MongoClients.create(settings);

The JDK natively supports Zlib compression. However, Snappy and Zstandard depend on open source Java implementations. To learn more about these implementations, see the following GitHub repositories:

To learn more about any of the methods or types discussed in this guide, see the following API documentation: