MongoDB vs Redis: Dokumen vs Tembolok Nilai Kunci
Peserta akan membandingkan model kueri MongoDB yang kaya fitur dengan kecepatan nilai-kunci Redis di memori, lalu mengidentifikasi beban kerja yang sesuai untuk masing-masing.
MongoDB vs Redis: Dokumen vs Tembolok Nilai Kunci adalah pelajaran MongoDB Academy gratis di CoddyKit. Ini adalah pelajaran 1 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar MongoDB Academy, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus MongoDB Academy mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
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.
Pertanyaan yang Sering Diajukan
Apakah pelajaran “MongoDB vs Redis: Dokumen vs Tembolok Nilai Kunci” gratis?
Ya — teks lengkap “MongoDB vs Redis: Dokumen vs Tembolok Nilai Kunci” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus MongoDB Academy, upgrade ke CoddyKit PRO. Kursus MongoDB Academy mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “MongoDB vs Redis: Dokumen vs Tembolok Nilai Kunci”?
Peserta akan membandingkan model kueri MongoDB yang kaya fitur dengan kecepatan nilai-kunci Redis di memori, lalu mengidentifikasi beban kerja yang sesuai untuk masing-masing. Kamu berlatih MongoDB Academy dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai MongoDB Academy?
Tidak diperlukan pengalaman sebelumnya. MongoDB Academy di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 1 dari 4.
Berapa lama pelajaran “MongoDB vs Redis: Dokumen vs Tembolok Nilai Kunci” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran MongoDB Academy ini?
Ya. Setiap pelajaran MongoDB Academy menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- MongoDB vs Redis: Dokumen vs Tembolok Nilai Kunci
- MongoDB vs Cassandra: Penulisan pada Skala Planet
- MongoDB vs DynamoDB: Pertukaran dalam Komputasi Awan Asli
- Kapan Menggunakan Basis Data Graf seperti Neo4j