$unwind: การแยกฟิลด์อาร์เรย์
ผู้เรียนจะคลี่ฟิลด์อาร์เรย์เป็นเอกสารแต่ละรายการด้วย $unwind และใช้ร่วมกับ $group เพื่อวิเคราะห์ข้อมูลแยกตามสมาชิก
$unwind: การแยกฟิลด์อาร์เรย์ เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Does $unwind Do?
The $unwind stage deconstructs an array field in a document into multiple output documents—one per array element. Each output document is a copy of the original document with the array field replaced by a single element from the array. This is essential for per-element analytics, like counting how many times each tag appears across all articles in a collection.
// Input document:
// { title: 'MongoDB Guide', tags: ['nosql', 'database', 'mongodb'] }
db.articles.aggregate([
{ $unwind: '$tags' }
]);
// Output: THREE documents:
// { title: 'MongoDB Guide', tags: 'nosql' }
// { title: 'MongoDB Guide', tags: 'database' }
// { title: 'MongoDB Guide', tags: 'mongodb' }Basic $unwind Syntax
The simplest form of $unwind is a string with the dollar-prefixed field path: { $unwind: '$arrayField' }. The extended object syntax allows additional options like preserving empty arrays and including the array index. For most cases, the simple string form is sufficient.
// Simple string form
db.products.aggregate([
{ $unwind: '$reviews' }
]);
// Extended object form with options
db.products.aggregate([
{ $unwind: {
path: '$reviews',
includeArrayIndex: 'reviewIndex', // add index field
preserveNullAndEmptyArrays: true // keep docs with no reviews
}}
]);The Missing Array Problem
By default, $unwind removes documents where the specified field is missing, null, or an empty array. This behavior is like an inner join: only documents with non-empty arrays pass through. To preserve documents with missing or empty arrays, set preserveNullAndEmptyArrays: true. This is important when the array field is optional and you don't want to lose the parent document.
// Default: documents without 'tags' are DROPPED
db.articles.aggregate([{ $unwind: '$tags' }]);
// Article with no tags: { title: 'Untitled' } -> EXCLUDED
// preserveNullAndEmptyArrays: documents are KEPT
db.articles.aggregate([{
$unwind: {
path: '$tags',
preserveNullAndEmptyArrays: true // keep docs with no tags
}
}]);
// { title: 'Untitled' } -> INCLUDED with tags: nullincludeArrayIndex for Element Position
The includeArrayIndex option adds a new field to each output document containing the 0-based index of the element in the original array. This is useful when the position in the array carries meaning—for example, the order of steps in a process, the rank of a search result, or the sequence of events in a log.
// Track which position each tag appeared at in the original array
db.articles.aggregate([{
$unwind: {
path: '$tags',
includeArrayIndex: 'tagPosition'
}
}]);
// { title: 'Guide', tags: 'nosql', tagPosition: 0 }
// { title: 'Guide', tags: 'database', tagPosition: 1 }
// { title: 'Guide', tags: 'mongodb', tagPosition: 2 }$unwind Followed by $group
The most common pattern in MongoDB aggregation is $unwind + $group: first flatten the array to get one document per element, then group to compute per-element statistics. For example, unwinding the tags array and then grouping by tag name gives you the count of articles per tag.
// Count how many articles use each tag
db.articles.aggregate([
{ $unwind: '$tags' }, // one doc per tag
{ $group: {
_id: '$tags', // group by tag value
count: { $sum: 1 } // count articles per tag
}},
{ $sort: { count: -1 } }, // most popular first
{ $limit: 20 } // top 20 tags
]);$unwind With $lookup Results
After a $lookup, the joined field is always an array. When the join is one-to-one (joining by a unique _id), you typically $unwind immediately to flatten the single-element array into an embedded object. This is such a common pattern that you'll see it in almost every pipeline that uses $lookup.
db.orders.aggregate([
{ $lookup: {
from: 'customers',
localField: 'customerId',
foreignField: '_id',
as: 'customer'
}},
// Flatten the single-element array
{ $unwind: '$customer' },
// Now access customer fields as objects
{ $project: {
orderId: '$_id',
amount: 1,
'customer.name': 1,
'customer.email': 1
}}
]);Flattening Nested Arrays
For documents with nested arrays (arrays inside arrays), you can use multiple consecutive $unwind stages. The first $unwind deconstructs the outer array, and the second deconstructs the inner array. Each stage multiplies the number of output documents, so be cautious with deep nesting to avoid explosive document expansion.
// Document: { course: 'Math', modules: [{ name: 'Algebra', lessons: ['L1', 'L2'] }] }
db.courses.aggregate([
{ $unwind: '$modules' }, // deconstruct modules array
{ $unwind: '$modules.lessons' } // deconstruct nested lessons array
]);
// Output:
// { course: 'Math', modules: { name: 'Algebra', lessons: 'L1' } }
// { course: 'Math', modules: { name: 'Algebra', lessons: 'L2' } }Calculating Array Element Statistics
A powerful use case for $unwind is computing statistics on individual array elements. For example, in an e-commerce database with orders containing line items (an array of sub-documents), unwinding line items lets you compute total revenue, average quantity, or top-selling items across all line items in all orders—not just per order.
// Total revenue and quantity per product across all orders
db.orders.aggregate([
{ $unwind: '$lineItems' }, // deconstruct line items
{ $group: {
_id: '$lineItems.productId',
totalRevenue: { $sum: { $multiply: ['$lineItems.price', '$lineItems.qty'] } },
totalQty: { $sum: '$lineItems.qty' },
orderCount: { $sum: 1 } // how many orders contained this product
}},
{ $sort: { totalRevenue: -1 } }
]);Avoiding $unwind When Possible
$unwind can dramatically multiply the number of documents in the pipeline (a document with a 100-element array becomes 100 documents after unwind). This increases memory usage and processing time for all subsequent stages. Always ask: 'Can I achieve this with an array expression operator like $size, $filter, or $map in a $project stage instead of unwinding?' Array expression operators are often faster because they don't expand the document count.
// Better: use $size in $project instead of $unwind + $count
// Avoid:
db.articles.aggregate([
{ $unwind: '$tags' },
{ $group: { _id: '$_id', tagCount: { $sum: 1 } } } // slow
]);
// Better:
db.articles.aggregate([{
$project: {
title: 1,
tagCount: { $size: { $ifNull: ['$tags', []] } } // fast
}
}]);$unwind Performance Impact
Because $unwind multiplies documents, it is usually the most expensive stage in a pipeline when applied to large arrays. Performance tips: apply $match and $project before $unwind to reduce the input document size and count; add a $match immediately after $unwind if you only care about specific elements; and limit the number of documents entering the unwind with an early $limit when applicable.
// Optimized order for $unwind pipelines:
db.orders.aggregate([
{ $match: { status: 'completed', createdAt: { $gte: thisMonth } } }, // 1. filter first
{ $project: { lineItems: 1, _id: 0 } }, // 2. project only needed fields
{ $unwind: '$lineItems' }, // 3. expand (smaller docs now)
{ $match: { 'lineItems.qty': { $gt: 5 } } }, // 4. filter expanded results
{ $group: { _id: '$lineItems.productId', count: { $sum: 1 } } }
]);Reconstructing Arrays After $unwind
After a $unwind + $group pipeline, you can use $push in the $group stage to rebuild an array from the processed elements. This pattern is useful for filtering or transforming array elements: unwind to get individual elements, apply per-element transformations or filters, then push back into a new array. This is more flexible than using $filter or $map for complex per-element logic.
// Filter out low-rated reviews per product, keep only rating >= 4
db.products.aggregate([
{ $unwind: '$reviews' },
{ $match: { 'reviews.rating': { $gte: 4 } } }, // per-element filter
{ $group: {
_id: '$_id',
name: { $first: '$name' },
goodReviews: { $push: '$reviews' } // rebuild filtered array
}}
]);
// Each product now has only its 4+ star reviews in goodReviewsQuick Check
Test your understanding of $unwind in the aggregation pipeline.
Lesson Recap
In this lesson you learned: $unwind creates one output document per array element, preserveNullAndEmptyArrays: true keeps documents with missing or empty arrays, and the classic $unwind + $group pattern enables per-element analytics like tag frequency counts. Next up we explore $addFields, $replaceRoot, and $mergeObjects.
คำถามที่พบบ่อย
บทเรียน “$unwind: การแยกฟิลด์อาร์เรย์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “$unwind: การแยกฟิลด์อาร์เรย์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “$unwind: การแยกฟิลด์อาร์เรย์”
ผู้เรียนจะคลี่ฟิลด์อาร์เรย์เป็นเอกสารแต่ละรายการด้วย $unwind และใช้ร่วมกับ $group เพื่อวิเคราะห์ข้อมูลแยกตามสมาชิก คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “$unwind: การแยกฟิลด์อาร์เรย์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- $lookup: การเชื่อมคอลเลกชันในไปป์ไลน์
- $unwind: การแยกฟิลด์อาร์เรย์
- $addFields, $replaceRoot และ $mergeObjects
- $out และ $merge: การเขียนผลลัพธ์ของไปป์ไลน์