MongoDB sort () method
Using the sort () method to sort the data in MongoDB, the sort () method can specify the sorted field by parameter and use 1 and-one to specify the sort, where 1 is sorted in ascending order, and-1 is used in descending order. Grammar
The basic syntax for the sort () method is as follows:
>db. Collection_name.find (). Sort ({key:1})
Instance
The data in the Col collection is as follows:
{"_id": ObjectId ("56066542ade2f21f36b0313a"), "title": "PHP Tutorial", "description": "PHP is a powerful server-side scripting language for creating dynamic interactive sites." ", by": "Rookie Tutorial", "url": "Http://www.runoob.com", "tags": ["PHP"], "likes": "
{_id": ObjectId ("56066549ade 2f21f36b0313b ")," title ":" Java Tutorial "," description ":" Java is a high-level programming language introduced by Sun Microsystems in May 1995. " ", by": "Rookie Tutorial", "url": "Http://www.runoob.com", "tags": ["Java"], "likes": "The" "
_id": ObjectId ("5606654fad e2f21f36b0313c ")," title ":" MongoDB Tutorial "," description ":" MongoDB is a Nosql database "," by ":" Rookie Tutorial "," url ":" Http://www.runo Ob.com "," tags ": [" MongoDB "]," likes ": 100}
The following example shows the data in the Col collection in descending order by field likes:
>db.col.find ({},{"title": 1,_id:0}). Sort ({"Likes": -1})
{"title": "PHP Tutorial"}
{"title": "Java Tutorial"}
{"Ti Tle ": MongoDB Tutorial"}
>
Note: If you do not specify how the sort () method is sorted, the default is in ascending order of the document.