$sort
The $sort update modifier orders array elements when used with the $push operator. It arranges array elements in ascending or descending order based on specified field values or the elements themselves.
Parameters
-
field: The array field to modify. -
order: Use1for ascending order or-1for descending order.
Example (MongoDB Shell)
The following example demonstrates using the $sort modifier with $push to add new quiz scores and keep them sorted in descending order.
Create sample documents
db.students.insertOne({ _id: 1, name: "Bob", quizzes: [ { score: 85, date: "2024-01-15" }, { score: 92, date: "2024-02-10" } ] });
Query example
db.students.updateOne( { _id: 1 }, { $push: { quizzes: { $each: [{ score: 78, date: "2024-03-05" }], $sort: { score: -1 } } } } )
Output
{
"_id" : 1,
"name" : "Bob",
"quizzes" : [
{ "score" : 92, "date" : "2024-02-10" },
{ "score" : 85, "date" : "2024-01-15" },
{ "score" : 78, "date" : "2024-03-05" }
]
}
Code examples
To view a code example for using the $sort update modifier, choose the tab for the language that you want to use: