0Pricing
MongoDB Academy · レッスン

MongoDB と Redis:ドキュメントとキーバリューキャッシュ

MongoDB の柔軟なクエリモデルと、Redis のインメモリ・キーバリュー処理の高速性を比較し、それぞれに適したワークロードを見極めます。

「MongoDB と Redis:ドキュメントとキーバリューキャッシュ」はCoddyKit上の無料MongoDB Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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時間対応のAIチューター)、MongoDB Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 MongoDB Academyコースには全4レッスンが含まれています。

「MongoDB と Redis:ドキュメントとキーバリューキャッシュ」で何を学びますか?

MongoDB の柔軟なクエリモデルと、Redis のインメモリ・キーバリュー処理の高速性を比較し、それぞれに適したワークロードを見極めます。 ブラウザで直接実行するハンズオンコードでMongoDB Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

MongoDB Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのMongoDB Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「MongoDB と Redis:ドキュメントとキーバリューキャッシュ」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このMongoDB Academyレッスンでコードを書いて実行できますか?

はい。すべてのMongoDB Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. MongoDB と Redis:ドキュメントとキーバリューキャッシュ
  2. MongoDB と Cassandra:惑星規模の書き込み
  3. MongoDB と DynamoDB:クラウドネイティブなトレードオフ
  4. Neo4j のようなグラフデータベースを使う場面
← MongoDB Academyに戻る