MongoDB vs Redis: Documents vs Key-Value Cache
Learners will contrast MongoDB's rich query model with Redis's in-memory key-value speed and identify workloads that belong in each.
MongoDB vs Redis: Documents vs Key-Value Cache is a free MongoDB Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the MongoDB Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Different Tools for Different Jobs
MongoDB and Redis are both NoSQL databases but solve fundamentally different problems. MongoDB is a general-purpose document database designed for rich querying, flexible schemas, and durable persistence. Redis is an in-memory data structure store designed for sub-millisecond latency, simple access patterns, and ephemeral or semi-persistent data. Understanding when to use each — and when to use both together — is a critical architectural skill.
MongoDB's Core Strengths
MongoDB excels when you need: rich query capability (filter by any field, nested documents, arrays); flexible schema (different documents can have different fields); durable persistence (data survives restarts with configurable write concerns); large document sizes (up to 16 MB vs Redis's string size limits); and aggregation pipelines for complex server-side transformations. MongoDB is the right choice for your application's primary data store.
Redis's Core Strengths
Redis excels when you need: sub-millisecond latency (data lives entirely in RAM); simple key-value access (get/set by key, no complex queries); rich data structures (strings, lists, sets, sorted sets, hashes, streams — all in-memory); atomic operations (increment, push, pop — race-condition-safe without transactions); and built-in TTL per key for automatic expiration. Redis is the right choice for caching, sessions, queues, and pub/sub.
The Classic Pattern: MongoDB + Redis Together
Most production applications use both: MongoDB as the primary durable datastore and Redis as a caching layer in front of it. The application checks Redis first (cache hit → return instantly), and falls back to MongoDB on a miss (cache miss → query MongoDB → store result in Redis with TTL). This pattern dramatically reduces MongoDB load and delivers Redis's sub-millisecond response times to users.
const redis = require('redis').createClient()
const client = await MongoClient.connect(process.env.MONGO_URI)
async function getProduct(productId) {
const cacheKey = 'product:' + productId
// 1. Check Redis cache
const cached = await redis.get(cacheKey)
if (cached) return JSON.parse(cached) // cache hit
// 2. Cache miss — fetch from MongoDB
const product = await client.db('shop').collection('products').findOne({ _id: new ObjectId(productId) })
// 3. Store in Redis with 5-minute TTL
await redis.setEx(cacheKey, 300, JSON.stringify(product))
return product
}Redis for Session Storage
HTTP sessions need fast key-based lookup (session ID → session data), automatic expiration (TTL equals session timeout), and high concurrency. These requirements make Redis ideal and MongoDB overkill for session storage. connect-redis is a popular Node.js library that plugs Redis directly into Express session middleware, replacing the default in-memory store.
const session = require('express-session')
const RedisStore = require('connect-redis').default
app.use(session({
store: new RedisStore({ client: redis }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { secure: true, maxAge: 3600000 } // 1 hour
}))
// Session data stored in Redis — instant lookup, auto-expiryRedis for Rate Limiting
Rate limiting requires counting requests per user per time window atomically. Redis's INCR command increments a counter and is atomic, making it perfect for this. Set a key like rate:userId:minute with a TTL of 60 seconds, increment on each request, and reject if the counter exceeds the limit. Implementing this in MongoDB would require transactions and is far more complex.
async function checkRateLimit(userId, maxRequests = 100) {
const key = 'rate:' + userId + ':' + Math.floor(Date.now() / 60000)
const count = await redis.incr(key)
if (count === 1) {
await redis.expire(key, 60) // set TTL on first increment
}
if (count > maxRequests) {
throw new Error('Rate limit exceeded')
}
return { remaining: maxRequests - count }
}Redis Sorted Sets for Leaderboards
Redis sorted sets (ZADD, ZRANGE, ZRANK) are perfect for real-time leaderboards. Each member has a score, and Redis maintains them in sorted order automatically. Fetching the top 100 players or finding a specific player's rank is O(log N) — far faster than a MongoDB find().sort().limit() query on a large collection.
// Add/update player score
await redis.zAdd('leaderboard:game', [
{ score: 9842, value: 'player:alice' },
{ score: 7210, value: 'player:bob' }
])
// Top 10 players (highest scores)
const top10 = await redis.zRange('leaderboard:game', 0, 9, { REV: true, WITHSCORES: true })
// Player's rank (0-indexed)
const rank = await redis.zRevRank('leaderboard:game', 'player:alice')
console.log('Alice rank:', rank + 1)When MongoDB Beats Redis
Choose MongoDB over Redis when: the data must survive restarts reliably (Redis persistence is optional and slower); you need complex queries across multiple fields; document sizes exceed a few megabytes; you need ACID transactions across multiple documents; or your dataset is larger than available RAM (Redis must fit in memory; MongoDB pages to disk). For your core domain data — users, orders, products — MongoDB is the right store.
When Redis Beats MongoDB
Choose Redis over MongoDB when: you need sub-millisecond response times and RAM budget allows; access patterns are key-based lookups with no need to search by value; data is transient (sessions, caches, temporary state); you need pub/sub messaging or a simple task queue; or you need atomic counter increments for rate limiting, view counts, or inventory holds.
Data Model Comparison
MongoDB organises data as BSON documents in collections — each document can have a rich nested structure with arrays and sub-documents. Redis organises data as key → value pairs where values can be strings, lists, sets, sorted sets, or hashes, but nesting is not native. MongoDB documents are queried by any field; Redis values are only accessible by their exact key (or set/sorted-set members). This fundamental difference drives all other tradeoffs.
// MongoDB: query by any field
db.users.find({ city: 'Istanbul', age: { $gte: 18 } })
// Redis: access only by key (no ad-hoc field queries)
await redis.hGetAll('user:alice123') // get all fields of Alice's hash
// No equivalent to 'find all users in Istanbul' without a secondary indexPersistence and Durability Comparison
MongoDB writes are durable by default — with w: majority, a write is confirmed only after it is replicated to a majority of replica set members and written to the journal. Redis persistence is optional: RDB snapshots save the dataset periodically (data between snapshots can be lost on crash), and AOF logging can be configured for near-durable writes but adds latency. For mission-critical data, MongoDB provides stronger durability guarantees.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: MongoDB and Redis solve different problems — MongoDB for rich queryable persistent data, Redis for sub-millisecond key-based access to in-memory data, the classic pattern is to use both — MongoDB as primary store with Redis as a caching and ephemeral data layer, and Redis excels for sessions, rate limiting, leaderboards, and pub/sub while MongoDB excels for complex queries, large documents, and durable domain data. Next up we compare MongoDB with Cassandra.
Frequently asked questions
Is the “MongoDB vs Redis: Documents vs Key-Value Cache” lesson free?
Yes — the full text of “MongoDB vs Redis: Documents vs Key-Value Cache” is free to read here on the web, and the MongoDB Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the MongoDB Academy course, upgrade to CoddyKit PRO.
What will I learn in “MongoDB vs Redis: Documents vs Key-Value Cache”?
Learners will contrast MongoDB's rich query model with Redis's in-memory key-value speed and identify workloads that belong in each. You practise MongoDB Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start MongoDB Academy?
No prior experience is required. MongoDB Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “MongoDB vs Redis: Documents vs Key-Value Cache” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this MongoDB Academy lesson?
Yes. Every MongoDB Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- MongoDB vs Redis: Documents vs Key-Value Cache
- MongoDB vs Cassandra: Writes at Planet Scale
- MongoDB vs DynamoDB: Cloud-Native Trade-offs
- When to Use a Graph Database Like Neo4j