Docs Home / Node.js Driver / Connect / Connection Options

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.您可以启用驱动程序选项来压缩消息,从而减少MongoDB和您的应用程序之间通过网络传递的数据量。

The driver supports the following compression algorithms:驱动程序支持以下压缩算法:

  1. Snappy: available in MongoDB 3.6 and later.:在MongoDB 3.6及更高版本中可用。

  2. Zlib: available in MongoDB 3.6 and later.:在MongoDB 3.6及更高版本中可用。

  3. Zstandard: available in MongoDB 4.2 and later.:在MongoDB 4.2及更高版本中可用。

If you specify multiple compression algorithms, the driver selects the first one in the list supported by your MongoDB instance.如果您指定了多个压缩算法,驱动程序将选择MongoDB实例支持的列表中的第一个。

Note

When using the Snappy or Zstandard compression algorithm, you must add explicit dependencies.使用Snappy或Z标准压缩算法时,必须添加显式依赖关系

Specify Compression Algorithms指定压缩算法

You can enable compression for the connection to your MongoDB instance by specifying the algorithms in one of two ways:您可以通过以下两种方式之一指定算法,为与MongoDB实例的连接启用压缩:

  1. Adding the parameter to your connection string.将参数添加到连接字符串中。

  2. Specifying the compressors option in your MongoClientOptions.MongoClientOptions中指定compressors选项。

Connection String连接字符串

To enable compression using the connection string, add the compressors parameter in the connection string. You can specify one or more compression algorithms, separating them with commas:要使用连接字符串启用压缩,请在连接字符串中添加压缩器参数。您可以指定一个或多个压缩算法,用逗号分隔:

const uri =
"mongodb+srv://<user>:<password>@<cluster-url>/?compressors=snappy,zlib";

const client = new MongoClient(uri);
MongoClientOptions

To enable compression using the MongoClientOptions, pass the compressors option and the compression algorithm you want to use. You can specify one or more compression algorithms, separating them with commas:要使用MongoClientOptions启用压缩,请传递compressors选项和要使用的压缩算法。您可以指定一个或多个压缩算法,用逗号分隔:

const uri =
"mongodb+srv://<user>:<password>@<cluster-url>";

const client = new MongoClient(uri,
{
compressors: ["snappy"]
});

Specify compression algorithms using the following strings:使用以下字符串指定压缩算法:

Compression Algorithm Dependencies压缩算法相关性

To add the Snappy compression algorithm to your application, run the following code:要将Snappy压缩算法添加到您的应用程序中,请运行以下代码:

npm install --save snappy

To add the Zstandard compression algorithm to your application, run the following code:要将Zstandard压缩算法添加到您的应用程序中,请运行以下代码:

npm install --save @mongodb-js/zstd