对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

压缩网络流量

MongoDB驱动程序可以压缩发送到 MongoDB Server 和从MongoDB Server接收的消息。这减少了每次操作传输的数据量。压缩可以提高受限网络上的性能,并降低与运行MongoDB Atlas相关的数据传输成本。

压缩在传输协议级别运行,因此它适用于应用程序执行的每个操作。如果指定多个算法,驾驶员将使用列表中MongoDB Server也支持的第一个算法。

MongoDB驱动程序支持以下压缩算法:

MongoDB Atlas charges for data transferred across cloud regions, cloud providers, and between your infrastructure and MongoDB Atlas. Network compression reduces the amount of data that your application sends and receives, which can lower these data transfer costs. To learn more about pricing, see Data Transfer Costs.

网络压缩还有助于提高工作效率。压缩后的消息通过网络传输的时间更短,这可以缩短应用程序的响应时间。压缩还可以减少MongoDB流量使用的带宽,从而为同一网络上的其他应用程序留出更多带宽。

选择压缩算法时,请考虑以下准则:

  • 使用 Zstandard 在压缩效率和资源使用之间取得平衡。对于大多数应用程序来说,Zstandard 是一个不错的默认选择。

  • Snappy 用于需要最小计算开销的延迟敏感型应用程序。

  • 使用 Zlib 实现跨MongoDB驱动程序和环境的广泛兼容性。

提示

监控 CPU 使用率

Compression trades network bandwidth for CPU usage. After you enable network compression, monitor your application's CPU utilization to confirm that the trade-off benefits your workload. To learn more about these trade-offs, see the CPU Utilization and Network Compression in MongoDB blog post.

下表列出了每种压缩算法支持的最低驾驶员和MongoDB Server版本:

压缩算法
最低驱动程序版本
最低服务器版本

2.15

4.2

2.5

4.2

2.15

4.2

要为MongoDB连接启用网络压缩,请安装所需的依赖项并指定要使用的压缩算法。

某些压缩算法要求您安装额外的 gem。下表列出了每种算法及其所需的依赖项(如果有):

Compression Algorithm
依赖

snappy

Add the snappy gem to your application. To install, add gem 'snappy' to your Gemfile and run the bundle install command.

zlib

No additional gem required. Your application must contain the zlib standard library extension.

Zstandard

Add the zstd-ruby gem to your application. To install, add gem 'zstd-ruby' to your Gemfile and run the bundle install command.

If you enable Snappy or Zstandard without installing the required gem, the driver raises an unmet dependency error when creating Mongo::Client.

要为 MongoDB 实例的连接启用压缩,请通过以下方式之一指定要使用的算法:

  • 将算法作为参数添加到连接字符串中

  • Mongo::Client对象的 compressors 选项中指定算法

要使用连接字符串启用网络压缩,请添加 compressors 选项。 您可以将一种或多种算法指定为以逗号分隔的列表。

uri = "mongodb://<hostname>:<port>/?compressors=zlib,snappy"
client = Mongo::Client.new(uri)

要在客户端对象中启用压缩,请将 compressors 选项传递给 Mongo::Client 构造函数。

client = Mongo::Client.new(["<hostname>:<port>"],
compressors: ["zlib", "snappy"])