Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Sorting

MongoDB Sorting

In MongoDB, the sort() method is used to sort data. The sort() method can specify the sorting field through parameters, and use 1 and -1 to specify the sorting order, where 1 is ascending order and -1 is descending order.

Syntax

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



db.collection.find().sort({ field1: 1, field2: -1 })

Example

Sort by field in ascending order:

Example

// Sort by the age field in ascending order

db.

myCollection

.

find

(

)

.

sort

(

{

age

:

1

}

)

;

Sort by field in descending order:

Example

// Sort by the createdAt field in descending order

db.

myCollection

.

find

(

)

.

sort

(

{

createdAt

:

1

}

)

;

You can specify multiple fields for sorting, and MongoDB will sort in the order of the specified fields.

Example

// First sort by the age field in ascending order, then by the createdAt field in descending order

db.

myCollection

.

find

(

)

.

sort

(

{

age

:

1

,

createdAt

:

1

}

)

;

The data in the col collection is as follows:



{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP 教程", "description" : "PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。", "by" : "Runoob Tutorial", "url" : "http://www.runoob.com", "tags" : [ "php" ], "likes" : 200 }

{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java 教程", "description" : "Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。", "by" : "Runoob Tutorial", "url" : "http://www.runoob.com", "tags" : [ "java" ], "likes" : 150 }

{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "Runoob Tutorial", "url" : "http://www.runoob.com", "tags" : [ "mongodb" ], "likes" : 100 }

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



>db.col.find({},{"title":1,_id:0}).sort({"likes":-1})

{ "title" : "PHP 教程" }

{ "title" : "Java 教程" }

{ "title" : "MongoDB 教程" }

>

Notes

By using the sort() method, you can conveniently sort MongoDB query results to meet different sorting needs, and arrange documents in ascending or descending order as needed.