对于 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版本:

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

1.0

4.2

1.0

4.2

1.2

4.2

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

下表列出了每种算法及其所需的依赖项(如果有):

Compression Algorithm
依赖

snappy

Add the Snappy compression algorithm to your application by running the go get github.com/golang/snappy command.

zlib

The driver uses the built-in zlib package. Import the package by adding the import "compress/zlib" statement to your application files.

Zstandard

Add the Zstandard compression algorithm to your application by running the go get -u github.com/klauspost/compress command.

您可以通过以下方式之一指定算法,为MongoDB 部署的连接启用压缩:

  • 在连接字符串中设置压缩算法

  • Set the compression algorithm in a ClientOptions instance

要使用连接字符串启用压缩,请将压缩算法作为compressors参数的值添加到连接字符串中。 您可以指定一种或多种压缩算法,用逗号分隔:

opts := options.Client().ApplyURI("mongodb://localhost:27017/?compressors=snappy,zlib,zstd")
client, _ := mongo.Connect(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(opts)

使用以下字符串指定压缩算法:

有关本指南中概念的更多信息,请参阅以下文档: