Use Redis for Caching MongoDB Queries

By Anurag Singh

Updated on May 21, 2025

Use Redis for Caching MongoDB Queries

In this tutorial, we'll learn how to use Redis for caching MongoDB queries.

We understand how important it is for web applications to deliver fast, reliable user experiences. One common performance bottleneck is slow database queries, especially as applications scale. By using Redis as a caching layer for MongoDB queries, we can significantly improve response times and reduce the load on our database.

In this guide, we’ll walk through installing Redis and MongoDB, setting up a test database, and implementing query caching. This approach is ideal for web developers looking to optimize their applications for speed and efficiency.

Prerequisites

Before proceeding, make sure you have the following in place:

Use Redis for Caching MongoDB Queries

1. Installing Redis and MongoDB

First, we’ll install both Redis and MongoDB on an Ubuntu server. The same process applies to most Linux distributions, and similar steps can be used for Windows or macOS.

Update the system:

sudo apt update && sudo apt upgrade -y

Add the repository to the APT index, update it, and install Redis: https://redis.io/docs/latest/operate/oss_and_stack/install/archive/install-redis/install-redis-on-linux/

sudo apt-get install lsb-release curl gpg
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
sudo chmod 644 /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis

Redis will start automatically, and it should restart at boot time. If Redis doesn't start across reboots, you may need to manually enable it:

sudo systemctl enable redis-server
sudo systemctl start redis-server

Install MongoDB:

To import the MongoDB public GPG key, run the following command:

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
   sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
   --dearmor

Create the list file for Ubuntu 24.04 (Noble):

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list

Issue the following command to reload the local package database:

sudo apt-get update

To install the latest stable version, issue the following

sudo apt-get install -y mongodb-org

Start and enable MongoDB:

sudo systemctl start mongod
sudo systemctl enable mongod

Verify MongoDB is running:

sudo systemctl status mongod

2. Configure Redis for Caching

By default, Redis is configured to run as a general-purpose key-value store. To optimize Redis for caching, some configuration changes are needed.

2.1 Edit Redis Configuration

Open the Redis configuration file:

sudo nano /etc/redis/redis.conf

2.2 Set Max Memory Usage

Redis will work as a cache by evicting older data when memory is full. To limit Redis memory usage and configure eviction policies:

Find the following line and uncomment it (remove the #):

maxmemory <value>

Set the maximum memory limit, for example, 512MB:

maxmemory 512mb

2.3 Configure Eviction Policy

Redis uses eviction policies to decide how to handle memory limits. Below are the common policies:

  • noeviction: Returns an error when memory limit is reached.
  • allkeys-lru: Removes the least recently used (LRU) key across all keys.
  • volatile-lru: Removes the least recently used (LRU) key with an expiration.

For caching, it’s recommended to use the allkeys-lru policy:

maxmemory-policy allkeys-lru

2.4 Save and Restart Redis

Save the changes and restart Redis:

sudo systemctl restart redis-server

3. Creating a Test MongoDB Database

Let’s create a simple test database with a collection for demonstration.

Open the MongoDB shell:

mongosh

Inside the shell, run:

use webhosting_testdb
db.products.insertMany([
    { name: "Hosting Plan A", price: 199, stock: 15 },
    { name: "Hosting Plan B", price: 299, stock: 7 },
    { name: "Hosting Plan C", price: 399, stock: 2 }
])

Exit the shell:

exit

4. Setting Up a Node.js Web Application

Now we’ll connect everything with a basic Node.js application using express, mongodb, and redis packages.

Install Node.js and npm:

sudo apt install nodejs npm -y

Create a new project folder:

mkdir redis-mongodb-cache-demo
cd redis-mongodb-cache-demo
npm init -y

Install dependencies:

npm install express mongodb redis

5. Writing the Application Code

Let’s create app.js to handle caching with Redis before querying MongoDB.

nano app.js

Add following code:

const express = require('express');
const { MongoClient } = require('mongodb');
const redis = require('redis');

const app = express();
const mongoUrl = 'mongodb://localhost:27017';
const dbName = 'webhosting_testdb';
const redisClient = redis.createClient();

redisClient.connect();

MongoClient.connect(mongoUrl)
  .then(client => {
    const db = client.db(dbName);
    const productsCollection = db.collection('products');

    app.get('/products/:name', async (req, res) => {
      const { name } = req.params;

      // Check cache first
      const cachedProduct = await redisClient.get(name);
      if (cachedProduct) {
        return res.json({
          source: 'cache',
          data: JSON.parse(cachedProduct)
        });
      }

      // Fetch from MongoDB if not in cache
      const product = await productsCollection.findOne({ name });
      if (!product) {
        return res.status(404).json({ error: 'Product not found' });
      }

      // Store in Redis cache for 1 hour
      await redisClient.setEx(name, 3600, JSON.stringify(product));

      res.json({
        source: 'mongodb',
        data: product
      });
    });

    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
  })
  .catch(err => console.error('MongoDB Connection Error:', err));

6. Running the Application

Start the app:

node app.js

Access a product in the browser or via curl:

curl http://localhost:3000/products/Hosting%20Plan%20A
  • The first request fetches data from MongoDB and caches it in Redis.
  • Subsequent requests for the same product are served from Redis, dramatically improving speed.

7. Verifying Redis Caching

A. Monitor API Responses

After setting up caching in the application, test with repeated requests:

Make the first request:

curl http://localhost:3000/products/Hosting%20Plan%20A

The response should show "source": "mongodb", indicating a database hit.

Make the same request again:

curl http://localhost:3000/products/Hosting%20Plan%20A

This time, the response should show "source": "cache", confirming the data is coming from Redis.

B. Check Redis Directly

Open the Redis CLI:

redis-cli

View cached keys:

keys *

See the value for a key (replace with your actual product name):

get "Hosting Plan A"

This confirms the product data is stored in Redis.

C. Use Logging

In the Node.js app, we recommend logging whether data was served from MongoDB or Redis. This helps quickly confirm caching is working as expected.

2. Cleaning Up (Clearing Redis Cache)

A. Clear a Specific Cache Entry

To remove a single cached item (for example, when a product is updated):

In the Redis CLI:

del "Hosting Plan A"

Or programmatically in Node.js:

await redisClient.del("Hosting Plan A");

B. Flush All Cache

If we want to clear all cached data (use with caution, as this will remove everything):

In the Redis CLI:

FLUSHALL

This is useful during major updates, deployments, or debugging sessions.

C. Automate Cache Invalidation

In a real-world application, set up logic to automatically clear or update cache entries when MongoDB data changes. This can be handled in code whenever a create, update, or delete operation occurs.

Example (on update in Node.js):

// After updating the product in MongoDB
await redisClient.del(productName);

How Redis Caching Improves Performance

By adding Redis between our application and MongoDB:

  • Frequently requested data is delivered almost instantly.
  • MongoDB query load decreases, allowing it to serve more users efficiently.
  • Our web applications become more responsive, providing a better user experience.

Best Practices

  • Use meaningful cache keys (such as product IDs).
  • Set sensible expiry times (setEx) to ensure data remains fresh.
  • Clear or update the cache when database entries are updated or deleted.

Conclusion

Leveraging Redis as a caching layer for MongoDB queries is a powerful way to boost the performance of web applications. As a web hosting provider, we always recommend integrating caching solutions like Redis to keep sites fast, reliable, and ready to scale.

Looking for high-performance hosting that supports modern web stacks like Redis and MongoDB? Explore our hosting plans or reach out to our team—we’re here to help every step of the way.