Dragonfly

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

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?

Other Common MongoDB Performance Questions (and Answers)

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

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost