Navigation
This version will reach end of life on Feb 2018. To upgrade, go to the Learn more about upgrading your version of MongoDB.

$size (aggregation)

On this page

New in version 2.6.

Definition

$size

Counts and returns the total the number of items in an array.

$size has the following syntax:

{ $size: <expression> }

The argument for $size can be any expression as long as it resolves to an array. For more information on expressions, see Expressions.

Example

Consider a inventory collection with the following documents:

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }

The following aggregation pipeline operation use the $size to return the number of elements in the colors array:

db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            numberOfColors: { $size: "$colors" }
         }
      }
   ]
)

The operation returns the following:

{ "_id" : 1, "item" : "ABC1", "numberOfColors" : 3 }
{ "_id" : 2, "item" : "ABC2", "numberOfColors" : 1 }
{ "_id" : 3, "item" : "XYZ1", "numberOfColors" : 0 }