Course contentsShow
← Node.js
Lesson 869 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Choosing Between Document and Key-Value

You will match your data access patterns to the optimal NoSQL storage engine.

Choosing Between Document and Key-Value Stores

In this lesson, you will learn how to match your application's data access patterns to the optimal NoSQL storage engine: Document stores or Key-Value stores.

When building Node.js applications, the choice between these two engines depends entirely on how you query your data.

The Key-Value Approach

A Key-Value store (like Redis or DynamoDB) is optimized for high-speed, point-in-time lookups using a unique primary key. It treats your data as an opaque "blob." Because the database doesn't "see" inside the value, it cannot filter, sort, or perform complex queries on internal fields.

Use this when: You need ultra-low latency for simple operations, like fetching a user_session or a product_cache by ID.

// Quick fetch by ID
const session = await kvStore.get('session:123'); 

The Document Approach

A Document store (like MongoDB) is designed for rich data structures. It understands the internal schema of your data, allowing you to filter by specific fields, perform joins (via lookups), or run complex aggregations without fetching the entire object.

Use this when: Your application requires searching through data based on internal attributes, such as "find all users who signed up in the last 30 days" or "filter orders by status."

// Querying by internal fields
const activeOrders = await db.collection('orders').find({ status: 'pending' }).toArray();

Making the Decision

The trade-off is between query flexibility and raw performance.

If your Node.js application primarily performs simple "get" and "set" operations based on a known primary key, a Key-Value store will provide superior performance and simpler scaling. However, if your business logic requires exploring, filtering, or analyzing the properties within your data, the Document store is the correct choice, even if it introduces slightly more overhead.

Don't force a Document store to act like a Key-Value store just for speed, and don't struggle to write complex queries in a Key-Value store that lacks the indexing capabilities to handle them efficiently.

Key Takeaway: Choose a Key-Value store for high-speed primary key lookups, and a Document store when you need to query or filter data based on its internal structure.