Introducing Dragonfly Cloud! Learn More

Question: How does MongoDB support network compression?

Answer

MongoDB supports network compression to reduce the amount of data that's transferred over the network between the MongoDB server (mongod or mongos) and the clients. This can significantly improve performance, especially in bandwidth-constrained environments.

Enabling Network Compression

Network compression in MongoDB is configured through the net.compression.compressors setting on the MongoDB server and through connection string options or a configuration object on the client side. MongoDB uses the Snappy compressor by default if it's supported by both the client and the server. Starting from MongoDB 3.6, zlib and zstd (from MongoDB 4.2) compression are also available.

Server Configuration

To configure the compressors on the server side, you can set the net.compression.compressors option in the mongod/mongos configuration file:

net: compression: compressors: snappy,zlib,zstd

This setting specifies the list of compressors the server can use, in order of preference.

Client Configuration

On the client side, you specify the desired compressor(s) through the connection string or a client configuration object. Here's how you can do it in a MongoDB Node.js driver:

const { MongoClient } = require('mongodb'); const uri = 'mongodb://localhost/?compressors=snappy&zlibCompressionLevel=6'; const client = new MongoClient(uri); client.connect();

In this example, we request Snappy compression with zlib as a fallback, and we set the zlib compression level to 6.

Considerations

  • Not all MongoDB drivers support all compressors. Check the documentation for your specific driver to see which compressors are supported.
  • Compression can reduce network I/O at the cost of increased CPU usage. Test in your environment to find the optimal balance.
  • Compression is most effective with larger documents and operations that return many documents, such as find() queries returning many results.

By carefully selecting and configuring the appropriate network compression settings, you can optimize MongoDB's performance and resource usage in your specific environment.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.