MongoDB Academy · บทเรียน

เมื่อใดควรใช้ฐานข้อมูลกราฟอย่าง Neo4j

ผู้เรียนจะระบุปัญหาที่มีโครงสร้างเป็นกราฟ เช่น ระบบแนะนำ การตรวจจับการทุจริต และกราฟความรู้ ซึ่งการไล่สำรวจแบบเนทีฟของ Neo4j ทำงานได้ดีกว่าการเชื่อมต่อด้วย $lookup หลายขั้นใน MongoDB

บทเรียน 4 จาก 413 ขั้นตอน

เมื่อใดควรใช้ฐานข้อมูลกราฟอย่าง Neo4j เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

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
])

Neo4j and the Cypher Query Language

Neo4j is the most popular graph database, using the Cypher query language — a declarative, pattern-based language for graph traversal. A Cypher query describes the graph pattern you are looking for using ASCII-art notation: nodes in (), relationships in -[]->. The query engine finds all subgraphs matching the pattern efficiently using native index-free adjacency.

// Cypher: find Alice's second-degree connections (friends of friends)
MATCH (alice:User { name: 'Alice' })
      -[:FOLLOWS]->(:User)
      -[:FOLLOWS]->(foaf:User)
WHERE NOT (alice)-[:FOLLOWS]->(foaf)
  AND foaf <> alice
RETURN DISTINCT foaf.name, foaf.email
LIMIT 50

// This is O(connections traversed), not O(total users in DB)

Classic Graph Use Case: Recommendation Engines

Recommendation systems depend on traversing relationship networks: 'users who bought what you bought also bought X'. In a graph, each purchase is an edge between a user node and a product node. Finding collaborative filter recommendations is a 2-hop traversal: User → Product → (other Users who bought that Product) → (other Products those Users bought). Neo4j handles millions of such traversals per second. MongoDB's $graphLookup can do this but degrades at scale.

// Cypher: collaborative filtering recommendation
MATCH (me:User { _id: 'alice123' })
      -[:PURCHASED]->(p:Product)
      <-[:PURCHASED]-(other:User)
      -[:PURCHASED]->(rec:Product)
WHERE NOT (me)-[:PURCHASED]->(rec)
RETURN rec.name, COUNT(other) AS score
ORDER BY score DESC
LIMIT 10

Fraud Detection With Graph Analysis

Fraud rings often involve shared identity information: multiple accounts sharing the same device ID, phone number, IP address, or billing address. Graph databases excel at detecting these rings by traversing the relationships: 'find all accounts connected to this suspicious account through shared attributes within 3 hops'. Real-time fraud scoring at transaction time — querying a graph across millions of linked entities in milliseconds — is a native strength of Neo4j that MongoDB cannot match.

// Cypher: find fraud ring (accounts sharing device/phone/address)
MATCH (suspect:Account { id: 'acc-999' })
      -[:SHARES_DEVICE|SHARES_PHONE|SHARES_ADDRESS*1..3]-(related:Account)
WHERE related.status = 'active'
RETURN related.id, related.email
LIMIT 100

Knowledge Graphs

A knowledge graph models entities and their semantic relationships — like Wikipedia's information structured as a graph. Knowledge graphs power search engine entity recognition, AI assistants' factual answering, and enterprise ontologies. The graph model fits naturally: Person knows Person, Person worksAt Company, Company isLocatedIn City, City isCapitalOf Country. Traversing these semantic chains is what graph databases are built for.

When MongoDB's $graphLookup Is Sufficient

Not every graph problem needs Neo4j. MongoDB's $graphLookup handles tree and graph traversals reasonably well for: shallow hierarchies (fewer than 5–6 hops); modest graph sizes (thousands to low millions of nodes); and infrequent traversal queries that can afford higher latency. If graph queries are a secondary feature of an application primarily built around document data, keeping everything in MongoDB simplifies the stack considerably.

// MongoDB $graphLookup: category hierarchy traversal
db.categories.aggregate([
  { $match: { _id: 1 } },
  {
    $graphLookup: {
      from: 'categories',
      startWith: '$_id',
      connectFromField: '_id',
      connectToField: 'parentId',
      as: 'descendants',
      maxDepth: 5
    }
  }
])

When to Choose Neo4j Over MongoDB

Choose Neo4j (or another graph database) when: deep multi-hop traversals are a core feature (social networks, knowledge graphs, fraud detection); the relationship itself carries rich properties (e.g., a FOLLOWS edge storing when the follow happened and whether it is mutual); graph queries must return results in real time under high concurrency; or the entire domain is relationship-centric rather than entity-centric. For social media, identity graphs, network topology, and dependency graphs — reach for Neo4j.

Polyglot Persistence: Using Both

Many large systems use polyglot persistence — different databases for different concerns. A social platform might store user profiles and posts in MongoDB (rich document queries), friendship and interest graphs in Neo4j (fast traversal), session data in Redis (sub-millisecond lookup), and analytics in a columnar store. Each database does what it is best at. The complexity is managing consistency across systems, but the performance and scalability gains often justify it.

MongoDB vs Neo4j Data Model Comparison

In MongoDB, a social relationship is modelled as a document in a follows collection with followerId and followeeId fields. In Neo4j, it is a FOLLOWS edge directly connecting two User nodes. The graph model eliminates the intermediate collection and enables direct pointer-based traversal. The document model is better for fetching the user's profile data; the graph model is better for traversing their social connections.

// MongoDB: relationships as documents
{ _id: ObjectId(), followerId: ObjectId('alice'), followeeId: ObjectId('bob'), createdAt: new Date() }

// Neo4j Cypher equivalent:
// (alice:User)-[:FOLLOWS { createdAt: datetime() }]->(bob:User)
// Stored as direct pointer — no intermediate collection needed

Graph Properties and Relationship Types

Graph edges in Neo4j have a type (like a label) and can have properties. A social graph might have FOLLOWS, LIKES, PURCHASED, and REVIEWED edge types — each with their own properties. Cypher queries can match on edge type and filter on edge properties, enabling rich relationship queries. This is much more natural than storing a type field in a relationships collection in MongoDB and joining on it.

// Cypher: find products purchased within the last 7 days by connections
MATCH (me:User { id: 'alice' })
      -[:FOLLOWS*1..2]->(friend:User)
      -[p:PURCHASED]->(prod:Product)
WHERE p.purchasedAt >= datetime() - duration('P7D')
RETURN prod.name, COUNT(friend) AS friendsBought
ORDER BY friendsBought DESC
LIMIT 5

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: graph databases like Neo4j excel at deep multi-hop relationship traversals — recommendation engines, fraud detection, knowledge graphs — where MongoDB's $lookup chains degrade exponentially, Neo4j's Cypher language expresses graph patterns declaratively in a way no document query language can match, and polyglot persistence using MongoDB for document data and Neo4j for relationship traversal is a common production pattern. Next up we tackle the capstone: designing a production-ready MongoDB application architecture.

เริ่มต้นได้ฟรี

เรียนรู้ JavaScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
30
บทเรียน
120

คำถามที่พบบ่อย

บทเรียน “เมื่อใดควรใช้ฐานข้อมูลกราฟอย่าง Neo4j” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “เมื่อใดควรใช้ฐานข้อมูลกราฟอย่าง Neo4j” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เมื่อใดควรใช้ฐานข้อมูลกราฟอย่าง Neo4j”

ผู้เรียนจะระบุปัญหาที่มีโครงสร้างเป็นกราฟ เช่น ระบบแนะนำ การตรวจจับการทุจริต และกราฟความรู้ ซึ่งการไล่สำรวจแบบเนทีฟของ Neo4j ทำงานได้ดีกว่าการเชื่อมต่อด้วย $lookup หลายขั้นใน MongoDB คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “เมื่อใดควรใช้ฐานข้อมูลกราฟอย่าง Neo4j” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. MongoDB เทียบกับ Redis: เอกสารกับแคชคีย์-ค่า
  2. MongoDB เทียบกับ Cassandra: การเขียนข้อมูลในระดับทั่วโลก
  3. MongoDB เทียบกับ DynamoDB: ข้อแลกเปลี่ยนของระบบคลาวด์เนทีฟ
  4. เมื่อใดควรใช้ฐานข้อมูลกราฟอย่าง Neo4j
← กลับไปที่ MongoDB Academy