MongoDB Academy · Lekcja

$push i $addToSet: tworzenie tablic w grupach

Nauczą się Państwo zbierać wartości z pogrupowanych dokumentów do tablic i usuwać duplikaty za pomocą $addToSet.

Lekcja 2 z 413 kroki

$push i $addToSet: tworzenie tablic w grupach to bezpłatna lekcja MongoDB Academy na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej MongoDB Academy, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs MongoDB Academy zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Bezpłatny start

Ucz się JavaScript dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
30
Lekcje
120

Często zadawane pytania

Czy lekcja „$push i $addToSet: tworzenie tablic w grupach” jest bezpłatna?

Tak — pełny tekst „$push i $addToSet: tworzenie tablic w grupach” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu MongoDB Academy, przejdź na CoddyKit PRO. Kurs MongoDB Academy zawiera 4 lekcji w sumie.

Co nauczysz się w „$push i $addToSet: tworzenie tablic w grupach”?

Nauczą się Państwo zbierać wartości z pogrupowanych dokumentów do tablic i usuwać duplikaty za pomocą $addToSet. Ćwiczysz MongoDB Academy z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć MongoDB Academy?

Nie wymagamy żadnego doświadczenia. MongoDB Academy w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „$push i $addToSet: tworzenie tablic w grupach”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji MongoDB Academy?

Tak. Każda lekcja MongoDB Academy zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. $sum, $avg, $min, $max: agregacja numeryczna
  2. $push i $addToSet: tworzenie tablic w grupach
  3. Akumulatory $first, $last oraz $top/$bottom
  4. Funkcje okna za pomocą $setWindowFields
← Powrót do MongoDB Academy