OPTIONS

$size (aggregation)

New in version 2.6.

Definition

$size

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

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

Example

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" : [
      "Amy",
      "Donnel",
      "Jack",
      "James"
  ]
}

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.

db.survey.aggregate(
   [
      {
         $group: {
            _id: "$street",
            numResidents: { $sum: {$size: "$occupants" } }
         }
      }
   ]
)