Sorting an array of documents
In this example, we are sorting all the documents of articles field in ascending order.
db.contributor.update({name: "Suman" }, {$push: { articles: { $each: [], $sort: 1 }}}) |
MongoDB – $sort Modifier
MongoDB provides different types of array update operators to update the values of the array fields in the documents and $sort modifier is one of them. This modifier is used to order the items of the array during $push operation or sort the items of the array in ascending or descending order during $push operation.
Syntax:
{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $sort: <sort specification> } } }
- If you want to sort the items (that are not documents) of the array or the array items(that are documents) in ascending order, then set the value of the
$sort
modifier to 1. - If you want to sort the items (that are not documents) of the array or the array items(that are documents) in descending order, then set the value of the
$sort
modifier to -1. - If the array items are documents and you want to sort fields of the documents, then specify a sort document with the field and the order (ascending or descending order), i.e., { <field>: 1 } or { <field>: -1 }.
Note: Please do not mention the containing array field in the sort specification, like { “myArray.field”: 1} it is wrong. - Modifier must appear with
$each
modifier in the$push
operator. You are allowed to pass an emptyarray[]
in the$each
modifier which help$sort
modifier to show its effect. If you use the $sort modifier without$each
modifier, then you will get an error. - This modifier can sort the items of the array that are not documents.
- If the array items are documents, then this modifier can sort by either the whole document or by a specified field in the documents.
In the following examples, we are working with:
Database: w3wiki
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs.