Docs Menu
Docs Home
/ / /
Go Driver
/ /

Network Compression

On this page

  • Overview
  • Specify Compression Algorithms
  • Compression Algorithm Dependencies
  • Additional Information
  • API Documentation

In this guide, you can learn how to enable network compression by using the Go driver. You can specify a client option to compress messages, which reduces the amount of data passed over the network between MongoDB and your application.

The Go driver supports the following compression 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.

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

You must add dependencies to use the Snappy or Zstandard compression algorithm. For more information, see the Compression Algorithm Dependencies section of this guide.

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

  • Set the compression algorithm in your connection string.

  • Set the compression algorithm in a ClientOptions instance.

To enable compression by using the connection string, add the compression algorithm as the value of the compressors parameter to your connection string. You can specify one or more compression algorithms separated by commas:

opts := options.Client().ApplyURI("mongodb://localhost:27017/?compressors=snappy,zlib,zstd")
client, _ := mongo.Connect(context.TODO(), opts)

To enable compression by specifying a ClientOptions instance, pass one or more compression algorithms to the SetCompressors() method as a string array:

opts := options.Client().SetCompressors([]string{"snappy", "zlib", "zstd"})
client, _ := mongo.Connect(context.TODO(), opts)

Specify compression algorithms by using the following strings:

To add the Snappy compression algorithm to your application, run the following code:

go get github.com/golang/snappy

To add the Zstandard compression algorithm to your application, run the following code:

go get -u github.com/klauspost/compress

To add the Zlib compression algorithm to your application, import the built-in zlib package. You must add the following import statement to application files that instantiate a Client with Zlib compression:

import "compress/zlib"

For more information about the concepts in this guide, see the following documentation:

  • Connection URI in the Connection Guide

  • Connection String Compression Options in the Server manual

  • The zlib package Go documentation

Back

Connection Guide