$slice (aggregation)

Definition

  • $slice

New in version 3.2.

Returns a subset of an array.

$slice has one of two syntax forms:

The following syntax returns elements from either the start or endof the array:

  1. { $slice: [ <array>, <n> ] }

The following syntax returns elements from the specified position inthe array:

  1. { $slice: [ <array>, <position>, <n> ] }

OperandDescription<array>Any valid expression as long asit resolves to an array.<position>Optional. Any valid expression as longas it resolves to an integer.

  • If positive, $slice determines the starting position fromthe start of the array. If <position> is greater than the number ofelements, the $slice returns an empty array.
  • If negative, $slice determines the starting position fromthe end of the array. If the absolute value of the <position> isgreater than the number of elements, the starting position is the startof the array.<n>Any valid expression as long as itresolves to an integer. If <position> is specified, <n> mustresolve to a positive integer.

  • If positive, $slice returns up to the first nelements in the array. If the <position> is specified,$slice returns the first n elements starting from theposition.

  • If negative, $slice returns up to the last n elementsin the array. n cannot resolve to a negative number if<position> is specified.

For more information on expressions, see Expressions.

Behavior

ExampleResults
  1. { $slice: [ [ 1, 2, 3 ], 1, 1 ] }
  1. [ 2 ]
  1. { $slice: [ [ 1, 2, 3 ], -2 ] }
  1. [ 2, 3 ]
  1. { $slice: [ [ 1, 2, 3 ], 15, 2 ] }
  1. [ ]
  1. { $slice: [ [ 1, 2, 3 ], -15, 2 ] }
  1. [ 1, 2 ]

Example

A collection named users contains the following documents:

  1. { "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
  2. { "_id" : 2, "name" : "li", favorites: [ "apples", "pudding", "pie" ] }
  3. { "_id" : 3, "name" : "ahn", favorites: [ "pears", "pecans", "chocolate", "cherries" ] }
  4. { "_id" : 4, "name" : "ty", favorites: [ "ice cream" ] }

The following example returns at most the first three elements in thefavorites array for each user:

  1. db.users.aggregate([
  2. { $project: { name: 1, threeFavorites: { $slice: [ "$favorites", 3 ] } } }
  3. ])

The operation returns the following results:

  1. { "_id" : 1, "name" : "dave123", "threeFavorites" : [ "chocolate", "cake", "butter" ] }
  2. { "_id" : 2, "name" : "li", "threeFavorites" : [ "apples", "pudding", "pie" ] }
  3. { "_id" : 3, "name" : "ahn", "threeFavorites" : [ "pears", "pecans", "chocolate" ] }
  4. { "_id" : 4, "name" : "ty", "threeFavorites" : [ "ice cream" ] }