- MongoDB CRUD Operations >
- MongoDB CRUD Tutorials >
- Limit Number of Elements in an Array after an Update
Limit Number of Elements in an Array after an Update¶
New in version 2.4.
Synopsis¶
Consider an application where users may submit many scores (e.g. for a test), but the application only needs to track the top three test scores.
This pattern uses the $push operator with the
$each, $sort, and $slice
modifiers to sort and maintain an array of fixed size.
Important
The array elements must be documents in order to use the
$sort modifier.
Pattern¶
Consider the following document in the collection students:
The following update uses the $push operator with:
- the
$eachmodifier to append to the array 2 new elements, - the
$sortmodifier to order the elements by ascending (1) score, and - the
$slicemodifier to keep the last3elements of the ordered array.
Note
When using the $sort modifier on the array element,
access the field in the subdocument element directly instead of
using the dot notation on the array field.
After the operation, the document contains only the top 3 scores in
the scores array: