Docs Menu

Query Cache Middleware Configuration

In this guide, you can learn how to configure your application to use query cache middleware. Query cache middleware allows you to activate the Query Cache for each request to store your query results. This can improve your application speed and efficiency by reducing the number of calls your application must make to the database.

The Ruby driver provides a Rack middleware which enables the query cache during each web request. The following code demonstrates how to enable the Query Cache Middleware in a Ruby on Rails application:

config/application.rb
# Add Mongo::QueryCache::Middleware at the bottom of the middleware
# stack or before other middleware that queries MongoDB.
config.middleware.use Mongo::QueryCache::Middleware

To learn more about using Rack middleware in Rails applications, see Configuring Middleware Stack in the Rails documentation.

The Ruby driver provides Query Cache Middleware for Active Job. You can enable it for all jobs in an initializer, as shown in the following code:

config/initializers/active_job.rb
# Enable Mongo driver query cache for Active Job
ActiveSupport.on_load(:active_job) do
include Mongo::QueryCache::Middleware::ActiveJob
end

You can also enable it for a specific job class, as shown in the following code:

class MyJob < ActiveJob::Base
include Mongo::QueryCache::Middleware::ActiveJob
end