Overview
MongoDB drivers can compress the messages sent to and received from MongoDB Server. This reduces the amount of data transferred for each operation. Compression can improve performance over constrained networks and lower the data transfer costs associated with running MongoDB Atlas.
Compression operates at the wire protocol level, so it applies to every operation that your application performs. If you specify more than one algorithm, the driver uses the first algorithm in your list that MongoDB Server also supports.
压缩算法
MongoDB drivers support the following compression algorithms:
Network Compression Benefits
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.
Network compression also has productivity benefits. Compressed messages take less time to transfer across the network, which can improve your application's response times. Compression also reduces the bandwidth that your MongoDB traffic uses, which leaves more bandwidth available for other applications on the same network.
When you choose a compression algorithm, consider the following guidelines:
Use Zstandard for a balance of compression efficiency and resource usage. Zstandard is a good default choice for most applications.
Use Snappy for latency-sensitive applications that require minimal computational overhead.
Use Zlib for broad compatibility across MongoDB drivers and environments.
提示
Monitor CPU Usage
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.
版本兼容性
所有版本的 Laravel 集成都支持每种网络压缩算法。
下表列出了每种算法支持的最低MongoDB Server版本:
启用网络压缩
要为MongoDB连接启用网络压缩,请执行以下步骤:
使用所需的依赖项构建MongoDB PHP扩展。扩展处理网络压缩,而不是 Laravel 集成。
指定要使用的压缩算法。
安装依赖项
由于 Laravel 集成使用MongoDB PHP扩展和MongoDB C驱动程序来实现网络压缩,因此您必须安装具有所需依赖项的C驾驶员。要查看这些依赖项,请参阅C驾驶员文档中的安装依赖项。
指定压缩算法
要为MongoDB实例的连接启用压缩,更新应用程序的 config/database.php 配置文件中的 connections大量。您可以通过以下方式之一指定压缩算法:
在
options大量中包含compressors选项在
dsn连接字符串中使用compressors参数
选择 Options Array 或 Connection String标签页查看指定所有可用压缩程序的示例:
设置 Zlib 压缩级别
如果您指定 Zlib 作为其中一种压缩算法,则可以使用 zlibCompressionLevel 选项来指定压缩级别。此选项接受 -1 和 9 之间的整数值,这些值具有以下效果:
-1: (默认)Zlib 使用其默认压缩级别(通常为
6)。0 :无压缩。
1 :速度最快,但压缩率最低。
9 :压缩最佳,但速度最慢。
选择 Options Array 或 Connection String标签页查看将 zlibCompressionLevel 选项设置为 1 的示例: