How to use $sort modifier with other modifiers with $push operator In MongoDB
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,
- The $each modifier is used to add multiple documents to the language array.
- The $sort modifier is used to sort all the items of the modified language array in ascending.
- The $slice modifier is used to keep only the first four sorted items of the language array.
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.
Contact Us