$push (aggregation)

Definition

  • $push
  • Returns an array of all values that result from applying anexpression to each document in a group of documents that share thesame group by key.

$push is only available in the$group stage.

$push has the following syntax:

  1. { $push: <expression> }

For more information on expressions, see Expressions.

Example

Consider a sales collection with the following documents:

  1. { "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
  2. { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
  3. { "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
  4. { "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
  5. { "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }
  6. { "_id" : 6, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-15T12:05:10Z") }
  7. { "_id" : 7, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T14:12:12Z") }

Grouping the documents by the day and the year of the date field,the following operation uses the $push accumulator tocompute the list of items and quantities sold for each group:

  1. db.sales.aggregate(
  2. [
  3. {
  4. $group:
  5. {
  6. _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
  7. itemsSold: { $push: { item: "$item", quantity: "$quantity" } }
  8. }
  9. }
  10. ]
  11. )

The operation returns the following results:

  1. {
  2. "_id" : { "day" : 46, "year" : 2014 },
  3. "itemsSold" : [
  4. { "item" : "abc", "quantity" : 10 },
  5. { "item" : "xyz", "quantity" : 10 },
  6. { "item" : "xyz", "quantity" : 5 },
  7. { "item" : "xyz", "quantity" : 10 }
  8. ]
  9. }
  10. {
  11. "_id" : { "day" : 34, "year" : 2014 },
  12. "itemsSold" : [
  13. { "item" : "jkl", "quantity" : 1 },
  14. { "item" : "xyz", "quantity" : 5 }
  15. ]
  16. }
  17. {
  18. "_id" : { "day" : 1, "year" : 2014 },
  19. "itemsSold" : [ { "item" : "abc", "quantity" : 2 } ]
  20. }