Open In App

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>
     }
  }
}

In the following examples, we are working with:



Database: GeeksforGeeks
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs.



Sorting array items that are not documents:

In this example, we are sorting all the items of the language field in ascending order.




db.contributor.update({name: "Suman"},
{$push: { language: { $each: ["Go", "Scala"],
 $sort: 1}}})

[/sourcecode]

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}}})

Sorting array of documents by a field:

In this example, we are sorting all the documents of articles field by tArticle field(descending order).




db.contributor.update({name: "Suman"}, 
                      {$push: { articles: { $each: [{language: "Go", tArticles: 120},
                        {language: "Perl", tArticles: 24}], $sort:{tArticles: -1}}}})

Updating the array using $sort modifier:

In this example, we are sorting the items of the language field in descending order.




db.contributor.update({}, 
                     {$push: {language: {$each:[], $sort: -1}}},
                       {multi: true})

Using $sort modifier with other modifiers with $push operator:

In this example, we are using the $sort modifier with other modifiers like $each and $slice with $push operator.




db.contributor.update({name: "Rohit"},
                      {$push: { language: { $each: ["C", "Go"], 
                        $sort: 1, $slice: 4}}})

Here,


Article Tags :