Navigation
This version of the documentation is archived and no longer supported.

$slice

$slice

New in version 2.4.

The $slice modifier limits the number of array elements during a $push operation. To project, or return, a specified number of array elements from a read operation, see the $slice projection operator instead.

To use the $slice modifier, it must appear with the $each modifier, and the $each modifier must be the first modifier for the $push operation.

db.collection.update( <query>,
                      { $push: {
                                 <field>: {
                                            $each: [ <value1>, <value2>, ... ],
                                            $slice: <num>
                                          }
                               }
                      }
                    )

The <num> is either a negative number or zero:

  • If <num> is negative, the array <field> contains only the last <num> elements.
  • If <num> is zero, the array <field> is an empty array.
db.students.update( { _id: 2 },
                    { $push: { grades: {
                                         $each: [ 80, 78, 86 ],
                                         $slice: -5
                                       }
                             }
                    }
                  )
←   $each $sort  →