Dragonfly

Question: How can I enable caching in MongoDB?

Answer

Caching is a crucial feature for enhancing the performance of database systems, including MongoDB. MongoDB internally uses caching to improve the efficiency of database operations. The primary mechanism for this is the WiredTiger storage engine's cache.

WiredTiger, MongoDB's default storage engine since version 3.2, automatically handles caching. However, you might want to configure cache settings for better performance tailored to your workload. Here’s how:

Configuring WiredTiger Cache Size

The WiredTiger cache size dictates how much data the storage engine keeps in memory. By default, WiredTiger will use up to 50% of the available RAM minus 1 GB. Adjusting the cache size can have significant impacts on performance, especially for read-heavy workloads.

You can set the cache size at startup through the --wiredTigerCacheSizeGB parameter or by setting storage.wiredTiger.engineConfig.cacheSizeGB in the configuration file (mongod.conf). Here's an example:

Via Command Line

mongod --wiredTigerCacheSizeGB 2

This command starts MongoDB with 2 GB of cache.

Via Configuration File (mongod.conf)

storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 2

After adding this to your configuration file, restart the MongoDB server for the changes to take effect.

Monitoring Cache Usage

Monitoring your cache usage is crucial to understand if your cache size setting is effective. You can use MongoDB's serverStatus command to check the current state of the cache:

db.serverStatus().wiredTiger.cache

This command returns several statistics about the cache, including the amount of data currently held in the cache.

Best Practices

By tuning the cache size according to your application's requirements and monitoring its effect, you can significantly improve the performance of your MongoDB deployment.

Was this content helpful?

Help us improve by giving us your feedback.

Other Common MongoDB Performance Questions (and Answers)

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

System Design on AWS

Switch & save up to 80%

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost