Overview
MongoDB 驱动程序可以压缩与 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 版本:
启用网络压缩
要对 MongoDB 连接启用网络压缩,请安装所需的依赖项,并指定要使用的压缩算法。
安装依赖项
下表列出了每种算法以及所需的依赖项(如果有):
压缩算法 | Dependencies |
|---|---|
snappy | 将 |
zlib | 无 |
Zstandard | 将 |
指定压缩算法
您可以通过以下两种方式之一来指定算法,以便为 MongoDB 实例的连接启用压缩:
将参数添加到连接字符串中。
在
MongoClientOptions中指定compressors选项。
要使用连接字符串启用压缩,请在连接字符串中添加compressors参数。 您可以指定一种或多种压缩算法,用逗号分隔:
const uri = "mongodb+srv://<user>:<password>@<cluster-url>/?compressors=snappy,zlib"; const client = new MongoClient(uri);
要使用MongoClientOptions启用压缩,请传递 compressors 选项和要使用的压缩算法。您可以指定一种或多种压缩算法,用逗号分隔:
const uri = "mongodb+srv://<user>:<password>@<cluster-url>"; const client = new MongoClient(uri, { compressors: ["snappy"] });
使用以下字符串指定压缩算法: