$size (aggregation)

New in version 2.6.



Counts and returns the total the number of items in an array. Consider the following syntax:

{ <field>: { $size: <array> } }


Given a survey collection that records town occupants by household, and that includes documents similar to the following:

  "_id" : ObjectId("524d82e535edde4707c684c5"),
  "household" : "Carter",
  "st_num" : 300,
  "street" : "North Bond Street",
  "occupants" : [

The following aggregation pipeline operation counts the number of residents on each street. The pipeline groups documents according to the street field and uses the $size operator to count the entries in each household’s occupants array. The pipeline uses $sum to add the number of residents on each street.

         $group: {
            _id: "$street",
            numResidents: { $sum: {$size: "$occupants" } }