Sorting the Metadata
In MongoDB, using the sort() method we can sort the metadata values. Let us discuss with the help of an example:
Example:
In the following examples, we are working with:
Database: gfg
Collections: metaexample
Document: Five documents
Now to sort metadata first we need to create the index using the createIndex() method.
Now, we sort the metadata
db.metaexample.find({$text:{$search:"MongoDB"}}, {score:{$meta: "textScore"}} ).sort({score:{$meta:"textScore"}})
Here, first, we search the text(i.e., MongoDB) using the {$meta: “textScore”} and after searching we sort the data and store the result in the score field. Here, we are sorting using “textScore”, so the data is sort in descending order.
Sorting Documents in MongoDB
Sorting is the way to arrange documents in ascending or descending order. In MongoDB, we can sort documents in ascending or descending order according to field data. To sort documents in a collection we use the sort() method. This method takes a parameter that contains a field: value pair that defines the sort order of the result set, if the value of this field is 1 then this method sorts the documents in ascending order, or if the value of this field is -1 then this method sorts the documents in descending order.
Syntax:
db.Collection_name.sort({field_name : 1 or -1})
Parameter:
This method takes a document that contains a field : value pair. If the value of this field is 1 then this method sorts the documents in ascending order, or if the value of this field is -1 then this method sorts the documents in descending order.
Return:
This method return sorted documents.
Examples:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Four documents contains name and age of the students.
- Return all the documents in ascending order of the age:
db.student.find().sort({age:1})
- Return all the documents in descending order of the age:
db.student.find().sort({age:-1})