MongoDB sort

MongoDB sort () method

Use MongoDB use sort () method to sort the data, sort () method to specify the sort column by argument, and use 1 and -1 to specify the sort of way, with 1 being arranged in ascending order, and -1 for descending sort.

grammar

sort () method of the basic syntax is as follows:

>db.COLLECTION_NAME.find().sort({KEY:1})

Examples

Col data collection are as follows:

{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP 教程", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "本教程", "url" : "https://w3resource.net/", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "本教程", "url" : "https://w3resource.net/", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "本教程", "url" : "https://w3resource.net/", "tags" : [ "mongodb" ], "likes" : 100 }

The following example demonstrates col data collection by the likes of the field in descending order:

>db.col.find({},{"title":1,_id:0}).sort({"likes":-1})
{ "title" : "PHP 教程" }
{ "title" : "Java 教程" }
{ "title" : "MongoDB 教程" }
>

NOTE: If you do not specify the sort () method to sort by default in ascending document.