0Pricing
MongoDB Academy · Aula

MongoDB versus Redis: documentos versus cache de chave-valor

Os alunos compararão o modelo avançado de consultas do MongoDB com a velocidade em memória de chave-valor do Redis e identificarão as cargas de trabalho adequadas para cada um.

MongoDB versus Redis: documentos versus cache de chave-valor é uma aula grátis de MongoDB Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de MongoDB Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de MongoDB Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Perguntas Frequentes

A aula “MongoDB versus Redis: documentos versus cache de chave-valor” é grátis?

Sim — o texto completo de “MongoDB versus Redis: documentos versus cache de chave-valor” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de MongoDB Academy, atualize para CoddyKit PRO. O curso de MongoDB Academy inclui 4 aulas no total.

O que vou aprender em “MongoDB versus Redis: documentos versus cache de chave-valor”?

Os alunos compararão o modelo avançado de consultas do MongoDB com a velocidade em memória de chave-valor do Redis e identificarão as cargas de trabalho adequadas para cada um. Você pratica MongoDB Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar MongoDB Academy?

Nenhuma experiência prévia é necessária. MongoDB Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “MongoDB versus Redis: documentos versus cache de chave-valor”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de MongoDB Academy?

Sim. Cada aula de MongoDB Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. MongoDB versus Redis: documentos versus cache de chave-valor
  2. MongoDB versus Cassandra: gravações em escala planetária
  3. MongoDB versus DynamoDB: compromissos nativos da nuvem
  4. Quando usar um banco de dados de grafos como o Neo4j
← Voltar para MongoDB Academy