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

$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.

db.collection.update( <query>,
                      { $push: {
                                 <field>: {
                                            $each: [ <document1>,
                                                     <document2>,
                                                     ...
                                                   ],
                                            $slice: <num>,
                                            $sort: <sort document>,
                                          }
                               }
                      }
                    )

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:

{ "_id": 3,
  "name": "joe",
  "quizzes": [
               { "id" : 1, "score" : 6 },
               { "id" : 2, "score" : 9 }
             ]
}

The following update appends additional documents to the quizzes array, sorts all the elements of the array by ascending score field, and slices the array to keep the last five elements:

db.students.update( { name: "joe" },
                    { $push: { quizzes: { $each: [ { id: 3, score: 8 },
                                                   { id: 4, score: 7 },
                                                   { id: 5, score: 6 } ],
                                          $sort: { score: 1 },
                                          $slice: -5
                                        }
                             }
                    }
                  )

After the update, the array elements are in order of ascending score field.:

{
  "_id" : 3,
  "name" : "joe",
  "quizzes" : [
                { "id" : 1, "score" : 6 },
                { "id" : 5, "score" : 6 },
                { "id" : 4, "score" : 7 },
                { "id" : 3, "score" : 8 },
                { "id" : 2, "score" : 9 }
              ]
}