MongoDB Academy · บทเรียน

$push และ $addToSet: การสร้างอาร์เรย์ในกลุ่ม

ผู้เรียนจะรวบรวมค่าจากเอกสารที่จัดกลุ่มไว้เป็นอาร์เรย์ และลบค่าซ้ำด้วย $addToSet

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

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

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

Collecting Values Into Arrays

When grouping documents, sometimes you want to collect individual field values into an array rather than compute a numeric aggregate. MongoDB provides two accumulators for this: $push and $addToSet. Both build an array result from grouped documents, but they differ in how they handle duplicate values. These accumulators are essential for producing denormalized or grouped results.

$push: Collecting All Values

$push appends the specified expression value to an array for every document in the group. It preserves duplicates—if multiple documents share the same value, that value will appear multiple times in the resulting array. The order of elements in the array corresponds to the order documents were processed, which may vary unless you sort before grouping.

db.orders.aggregate([
  {
    $group: {
      _id: '$customerId',
      // Collect all product IDs ordered by this customer
      orderedProducts: { $push: '$productId' },
      orderDates: { $push: '$createdAt' }
    }
  }
])

$addToSet: Collecting Unique Values

$addToSet works like $push except it deduplicates—each unique value is added to the array only once. The resulting array contains no repeated elements, similar to a mathematical set. The order of elements in the output is not guaranteed when using $addToSet, so do not depend on element ordering. Use it when you need a distinct list of values per group.

db.logs.aggregate([
  {
    $group: {
      _id: {
        year: { $year: '$timestamp' },
        month: { $month: '$timestamp' }
      },
      // Unique users who logged in this month
      uniqueUsers: { $addToSet: '$userId' },
      // Every event type including duplicates
      allEvents: { $push: '$eventType' }
    }
  }
])

Pushing Embedded Objects

You can $push entire subdocuments or computed objects, not just scalar values. By constructing an object expression, you can collect multiple fields from each document into a structured array element. This is useful for creating summary records that embed the details of each contributing document.

db.orders.aggregate([
  {
    $group: {
      _id: '$customerId',
      orderHistory: {
        $push: {
          orderId: '$_id',
          amount: '$amount',
          status: '$status',
          date: '$createdAt'
        }
      }
    }
  }
])

Combining $push With $sort

Because the order of elements in a $push array depends on document processing order, you should add a $sort stage before $group when the order of the collected array matters. For example, to collect orders in chronological order within each customer group, sort by date first. Note that sorting before $group prevents MongoDB from using many index optimizations, so consider the performance trade-off.

db.orders.aggregate([
  // Sort by date first so $push produces ordered arrays
  { $sort: { createdAt: 1 } },
  {
    $group: {
      _id: '$customerId',
      ordersInChronologicalOrder: {
        $push: {
          orderId: '$_id',
          date: '$createdAt',
          amount: '$amount'
        }
      }
    }
  }
])

Document Size Limits and Array Growth

MongoDB documents have a 16 MB size limit. When using $push in a $group stage, the resulting document could exceed this limit if a group contains many documents or if each pushed value is large. This is a runtime error, not a schema error. Mitigate this by filtering data before grouping, projecting only needed fields into $push, or using $limit combined with $sort to push only top-N items.

// Safe pattern: project only needed fields before pushing
db.events.aggregate([
  { $match: { year: 2024 } },
  {
    $project: {
      userId: 1,
      eventType: 1  // exclude large 'payload' field
    }
  },
  {
    $group: {
      _id: '$userId',
      events: { $push: '$eventType' }
    }
  }
])

Using $addToSet for Unique Tag Collections

A classic use case for $addToSet is aggregating unique tags or categories across documents in a group. For example, finding all unique skill tags across all job postings from each company, or all unique product categories purchased by each customer. The deduplication happens entirely server-side without requiring application-level filtering.

db.jobPostings.aggregate([
  {
    $group: {
      _id: '$companyId',
      uniqueSkills: { $addToSet: '$requiredSkills' },
      totalPostings: { $sum: 1 }
    }
  },
  { $sort: { totalPostings: -1 } }
])

Checking Array Size With $size in $project

After collecting values with $push or $addToSet, you often want to know how many items ended up in the array. Use $size in a subsequent $project or $addFields stage to compute the array length. You can also filter groups by array size using $match with $expr and $size.

db.orders.aggregate([
  {
    $group: {
      _id: '$customerId',
      products: { $addToSet: '$productId' }
    }
  },
  {
    $addFields: {
      uniqueProductCount: { $size: '$products' }
    }
  },
  // Only customers who bought 3 or more unique products
  { $match: { uniqueProductCount: { $gte: 3 } } }
])

Unwinding After Grouping

Sometimes you need to reverse a $push—take the grouped array and expand it back into individual documents for further processing. The $unwind stage does exactly this. A common pattern is: $group with $push to consolidate → $project to transform → $unwind to expand → further $group or $match to refine results.

db.orders.aggregate([
  { $group: { _id: '$customerId', products: { $push: '$productId' } } },
  // Expand back into per-product documents
  { $unwind: '$products' },
  // Now further filter or group by product
  {
    $group: {
      _id: '$products',
      customerCount: { $sum: 1 }
    }
  },
  { $sort: { customerCount: -1 } }
])

Real-World Pattern: User Activity Summary

A common production pattern is building a user activity summary document by grouping log events. Using $push and $addToSet together, you can generate a document that contains all event timestamps (ordered array via $push), all unique pages visited (deduped via $addToSet), and a total event count—all in one aggregation pass.

db.pageViews.aggregate([
  { $sort: { timestamp: 1 } },
  {
    $group: {
      _id: '$userId',
      visitTimestamps: { $push: '$timestamp' },
      uniquePages: { $addToSet: '$page' },
      totalVisits: { $sum: 1 }
    }
  },
  {
    $addFields: {
      uniquePageCount: { $size: '$uniquePages' }
    }
  }
])

$push vs $addToSet Comparison

To choose between $push and $addToSet, ask: do duplicates matter? Use $push when you need all values including repeats (e.g., event log, purchase history). Use $addToSet when you need only distinct values (e.g., unique tags, distinct pages visited). Remember that $addToSet does not guarantee any particular order of elements in the resulting array, while $push preserves insertion order relative to the pipeline input.

// $push — all values, order preserved
{ $push: '$tag' }  // ['mongodb', 'nosql', 'mongodb', 'database']

// $addToSet — unique values only, order not guaranteed
{ $addToSet: '$tag' }  // ['mongodb', 'database', 'nosql']

Quick Check

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

Lesson Recap

In this lesson you learned: $push collects all values including duplicates into an array, $addToSet collects only unique values with no guaranteed order, and both can push complex subdocuments and must respect the 16 MB document size limit. Next up we explore $first, $last, and the $top/$bottom accumulators for picking single documents per group.

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

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

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

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

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

บทเรียน “$push และ $addToSet: การสร้างอาร์เรย์ในกลุ่ม” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “$push และ $addToSet: การสร้างอาร์เรย์ในกลุ่ม”

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

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

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

บทเรียน “$push และ $addToSet: การสร้างอาร์เรย์ในกลุ่ม” ใช้เวลานานแค่ไหน

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

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

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

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

  1. $sum, $avg, $min, $max: การรวมข้อมูลเชิงตัวเลข
  2. $push และ $addToSet: การสร้างอาร์เรย์ในกลุ่ม
  3. ตัวรวม $first, $last และ $top/$bottom
  4. ฟังก์ชันหน้าต่างด้วย $setWindowFields
← กลับไปที่ MongoDB Academy