- Reference >
- Operators >
- Update Operators >
- Array Update Operators >
- $sort
$sort¶
-
$sort
¶ New in version 2.4.
The
$sort
modifier orders the elements of an array during a$push
operation. The elements of the array must be documents.$sort
modifies$push
updates that use both the$each
and$slice
modifiers, where$each
is the first modifier for the$push
operation.Important
The
<sort document>
only accesses the fields from the elements in the array and does not refer to the array<field>
.Consider the following example where the collection
students
contain the following document:The following update appends additional documents to the
quizzes
array, sorts all the elements of the array by ascendingscore
field, and slices the array to keep the last five elements:After the update, the array elements are in order of ascending
score
field.: