0Pricing
MongoDB Academy · Lesson

$push and $addToSet: Building Arrays in Groups

Learners will collect values from grouped documents into arrays and deduplicate them with $addToSet.

$push and $addToSet: Building Arrays in Groups is a free MongoDB Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the MongoDB Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “$push and $addToSet: Building Arrays in Groups” lesson free?

Yes — the full text of “$push and $addToSet: Building Arrays in Groups” is free to read here on the web, and the MongoDB Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the MongoDB Academy course, upgrade to CoddyKit PRO.

What will I learn in “$push and $addToSet: Building Arrays in Groups”?

Learners will collect values from grouped documents into arrays and deduplicate them with $addToSet. You practise MongoDB Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start MongoDB Academy?

No prior experience is required. MongoDB Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “$push and $addToSet: Building Arrays in Groups” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this MongoDB Academy lesson?

Yes. Every MongoDB Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. $sum, $avg, $min, $max: Numeric Aggregation
  2. $push and $addToSet: Building Arrays in Groups
  3. $first, $last, and $top/$bottom Accumulators
  4. Window Functions With $setWindowFields
← Back to MongoDB Academy