0Pricing
MongoDB Academy · Lesson

When to Use a Graph Database Like Neo4j

Learners will identify graph-shaped problems—recommendation engines, fraud detection, knowledge graphs—where Neo4j's native traversal outperforms $lookup chains in MongoDB.

What Is a Graph Database?

A graph database represents data as nodes (entities) and edges (relationships between entities). Each edge is a first-class object with a type and its own properties. Unlike relational or document databases where relationships are implied by foreign keys or embedded references, graph databases store relationships as explicit connections with O(1) traversal per hop — following a relationship takes constant time regardless of database size.

The Relationship Traversal Problem

Document and relational databases are optimised for finding entities — fetch a user by ID, query orders by status. They struggle with traversing relationships — 'find all friends of Alice's friends who bought the same product as Alice within the last month'. Each hop requires a $lookup or JOIN. Three hops deep means three nested joins. At 10 hops across millions of nodes, MongoDB's performance degrades exponentially while Neo4j's stays flat.

// MongoDB: 3-hop traversal — three nested $lookup stages
db.users.aggregate([
  { $match: { _id: aliceId } },
  { $lookup: { from: 'follows', localField: '_id', foreignField: 'followerId', as: 'following' } },
  { $unwind: '$following' },
  { $lookup: { from: 'follows', localField: 'following.followeeId', foreignField: 'followerId', as: 'followingOfFollowing' } },
  // Expensive and increasingly slow with scale
])

All lessons in this course

  1. MongoDB vs Redis: Documents vs Key-Value Cache
  2. MongoDB vs Cassandra: Writes at Planet Scale
  3. MongoDB vs DynamoDB: Cloud-Native Trade-offs
  4. When to Use a Graph Database Like Neo4j
← Back to MongoDB Academy