0PricingLogin
MongoDB Academy · Lesson

$push and $addToSet: Building Arrays in Groups

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

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' }
    }
  }
])

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