$size (aggregation)

New in version 2.6.

Definition

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

$size has the following syntax:

  1. { $size: <expression> }

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

Behavior

The argument for $size must resolve to an array. If theargument for $size is missing or does not resolve to anarray, $size errors.

Example

Consider a inventory collection with the following documents:

  1. { "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }
  2. { "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }
  3. { "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }
  4. { "_id" : 4, "item" : "ZZZ1", "description" : "product 4 - missing colors" }
  5. { "_id" : 5, "item" : "ZZZ2", "description" : "product 5 - colors is string", colors: "blue,red" }

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

  1. db.inventory.aggregate([
  2. {
  3. $project: {
  4. item: 1,
  5. numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} }
  6. }
  7. }
  8. ] )

The operation returns the following:

  1. { "_id" : 1, "item" : "ABC1", "numberOfColors" : 3 }
  2. { "_id" : 2, "item" : "ABC2", "numberOfColors" : 1 }
  3. { "_id" : 3, "item" : "XYZ1", "numberOfColors" : 0 }
  4. { "_id" : 4, "item" : "ZZZ1", "numberOfColors" : "NA" }
  5. { "_id" : 5, "item" : "ZZZ2", "numberOfColors" : "NA" }