0Pricing
MongoDB Academy · 강의

MongoDB와 Redis 비교: 문서와 키-값 캐시

학습자는 MongoDB의 풍부한 쿼리 모델과 Redis의 메모리 기반 키-값 처리 속도를 비교하고, 각 시스템에 적합한 작업 부하를 파악합니다.

MongoDB와 Redis 비교: 문서와 키-값 캐시은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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-expiry

Redis 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 index

Persistence 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.

자주 묻는 질문

“MongoDB와 Redis 비교: 문서와 키-값 캐시” 강의는 무료인가요?

네 — “MongoDB와 Redis 비교: 문서와 키-값 캐시” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“MongoDB와 Redis 비교: 문서와 키-값 캐시”에서 뭘 배우나요?

학습자는 MongoDB의 풍부한 쿼리 모델과 Redis의 메모리 기반 키-값 처리 속도를 비교하고, 각 시스템에 적합한 작업 부하를 파악합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“MongoDB와 Redis 비교: 문서와 키-값 캐시” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. MongoDB와 Redis 비교: 문서와 키-값 캐시
  2. MongoDB와 Cassandra 비교: 행성 규모의 쓰기 처리
  3. MongoDB와 DynamoDB 비교: 클라우드 네이티브 트레이드오프
  4. Neo4j와 같은 그래프 데이터베이스를 사용하는 경우
← MongoDB Academy(으)로 돌아가기