การทำงานของดัชนี B-Tree ใน MongoDB
ผู้เรียนจะติดตามวิธีที่ MongoDB จัดเก็บรายการดัชนีใน B-tree และวิธีที่ตัววางแผนการค้นหาเดินสำรวจต้นไม้เพื่อทำตามตัวกรอง
การทำงานของดัชนี B-Tree ใน MongoDB เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Indexes Exist
Without an index, MongoDB must scan every document in a collection to satisfy a query—this is called a collection scan (COLLSCAN). On a collection with millions of documents, a COLLSCAN can take seconds or even minutes. An index is a separate, ordered data structure that lets MongoDB jump directly to the matching documents in microseconds.
The B-Tree Data Structure
MongoDB uses a B-tree (balanced tree) to store index entries. A B-tree is organised as a hierarchy of nodes: a root node at the top, internal nodes in the middle, and leaf nodes at the bottom. Every node holds multiple key-value pairs and pointers to child nodes. The tree stays balanced—all leaf nodes are at the same depth—so lookups always take the same number of steps regardless of which value you search for.
How Index Entries Are Stored
When you create an index on a field like age, MongoDB builds a B-tree where each leaf node entry contains the indexed field value paired with a pointer (the RecordId) to the actual document on disk. The entries are sorted in ascending or descending order based on how you define the index. Because the tree is sorted, MongoDB can satisfy equality lookups, range queries, and sort operations all from the same structure.
// Index on 'age' field
db.users.createIndex({ age: 1 });
// MongoDB now has a sorted B-tree:
// 18 -> RecordId(doc1)
// 25 -> RecordId(doc4)
// 31 -> RecordId(doc2)
// 47 -> RecordId(doc7)The Query Planner and IXSCAN
Every query passes through MongoDB's query planner, which evaluates available indexes and chooses the most efficient execution plan. When the planner finds a suitable index, it uses an IXSCAN (index scan) stage instead of a COLLSCAN. An IXSCAN traverses the B-tree from root to the matching leaf nodes, then fetches only the relevant documents from disk using their RecordId pointers.
// See which plan MongoDB chose
db.users.find({ age: { $gt: 30 } }).explain('executionStats');Equality, Range, and Sort Index Use
A B-tree index supports three types of access patterns: equality lookups (find the exact key), range scans (traverse contiguous leaf nodes between two bounds), and sort operations (the tree is already ordered, so no in-memory sort is needed). This triple capability makes a well-placed index dramatically more useful than it might first appear.
// Equality - single leaf node lookup
db.users.find({ username: 'alice' });
// Range - scan contiguous leaf nodes
db.users.find({ age: { $gte: 20, $lte: 30 } });
// Sort - traverses tree in order, no sort stage
db.users.find({}).sort({ age: 1 });Index Direction: Ascending vs Descending
When you create an index with 1 the entries are stored in ascending order; -1 stores them in descending order. For a single-field index, direction doesn't matter much because MongoDB can traverse the B-tree in either direction. Direction becomes critical in compound indexes where the combination of directions must match the sort order your queries use.
// Ascending index
db.orders.createIndex({ createdAt: 1 });
// Descending index (useful for 'newest first' sorts)
db.orders.createIndex({ createdAt: -1 });Index Size and Memory
MongoDB tries to keep the working set of indexes in RAM (the WiredTiger cache). When an index fits entirely in memory, lookups are essentially free I/O operations. When an index is too large for RAM, MongoDB must page index nodes in from disk, which causes latency spikes. This is why you should keep indexes lean—only index the fields you actually query, and use projection to avoid returning unused data.
// Check index sizes in bytes
db.users.stats().indexSizes;
// Example output:
// { '_id_': 856064, 'age_1': 442368 }Covered Queries
A covered query is one where all the fields in the filter and projection are present in the index. MongoDB can answer such a query using only the index B-tree—it never has to fetch the actual document from disk. Covered queries are extremely fast and are worth designing for on your hottest read paths.
// Index on email and name
db.users.createIndex({ email: 1, name: 1 });
// Covered query: filter on email, project email+name only
// MongoDB only reads the index, never the document
db.users.find(
{ email: 'a@b.com' },
{ _id: 0, email: 1, name: 1 }
);The _id Index Is Always Present
Every MongoDB collection automatically has a unique B-tree index on _id. This default index is why lookups by _id are always fast, even on enormous collections. You cannot drop the _id index. All other indexes are optional and must be created explicitly by the developer or DBA.
// MongoDB creates this automatically:
// { '_id': 1 } (unique)
// Fast because _id is always indexed:
db.orders.findOne({ _id: ObjectId('64a1f...') });Write Overhead of Indexes
Indexes speed up reads but slow down writes. Every insert, update, or delete must update not only the document on disk but also every B-tree that indexes a field on that document. A collection with 10 indexes incurs 10 extra B-tree writes per insert. This trade-off means you should only create indexes that serve real query patterns—zombie indexes that nobody uses still pay the write tax.
// List all indexes and their sizes
db.users.getIndexes();
// Identify unused indexes (MongoDB 4.4+)
// $indexStats shows usage counts since last restart
db.users.aggregate([{ $indexStats: {} }]);Multikey Indexes for Arrays
When you index a field that contains an array, MongoDB creates a multikey index—it inserts one B-tree entry per array element. This allows queries like { tags: 'mongodb' } to use the index even though tags is an array. MongoDB detects array fields automatically and sets the multikey flag; you don't need to do anything special when creating the index.
// Document with array field
// { title: 'Guide', tags: ['mongodb', 'nosql', 'database'] }
// Single index creation
db.articles.createIndex({ tags: 1 });
// MongoDB creates THREE B-tree entries:
// 'database' -> RecordId
// 'mongodb' -> RecordId
// 'nosql' -> RecordId
// This query now uses IXSCAN
db.articles.find({ tags: 'mongodb' });Quick Check
Test your understanding of MongoDB B-Tree indexes from this lesson.
Lesson Recap
In this lesson you learned: MongoDB uses B-tree structures where sorted leaf entries point to document RecordIds, the query planner chooses IXSCAN over COLLSCAN when a suitable index exists, and indexes accelerate reads but add write overhead. Next up we explore creating single-field and compound indexes.
คำถามที่พบบ่อย
บทเรียน “การทำงานของดัชนี B-Tree ใน MongoDB” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การทำงานของดัชนี B-Tree ใน MongoDB” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การทำงานของดัชนี B-Tree ใน MongoDB”
ผู้เรียนจะติดตามวิธีที่ MongoDB จัดเก็บรายการดัชนีใน B-tree และวิธีที่ตัววางแผนการค้นหาเดินสำรวจต้นไม้เพื่อทำตามตัวกรอง คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การทำงานของดัชนี B-Tree ใน MongoDB” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การทำงานของดัชนี B-Tree ใน MongoDB
- การสร้างดัชนีฟิลด์เดียวและดัชนีผสม
- คุณสมบัติดัชนี: ไม่ซ้ำ กระจายบางส่วน บางส่วน และ TTL
- การอ่านผลลัพธ์จาก explain() เพื่อวินิจฉัยการค้นหา