要在MongoDB中排序,可以使用sort()
方法。
情况1-升序排列。语法如下-
db.yourCollectionName.find().sort({yourField:1});
情况2-降序排列。语法如下-
db.yourCollectionName.find().sort({yourField:-1});
为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.sortingDemo.insertOne({"Value":100}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f8e2ed3c9d04998abf006") } > db.sortingDemo.insertOne({"Value":1}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f8e31d3c9d04998abf007") } > db.sortingDemo.insertOne({"Value":150}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f8e34d3c9d04998abf008") } > db.sortingDemo.insertOne({"Value":250}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f8e37d3c9d04998abf009") } > db.sortingDemo.insertOne({"Value":5}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f8e3bd3c9d04998abf00a") } > db.sortingDemo.insertOne({"Value":199}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f8e3ed3c9d04998abf00b") } > db.sortingDemo.insertOne({"Value":243}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f8e44d3c9d04998abf00c") } > db.sortingDemo.insertOne({"Value":290}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f8e48d3c9d04998abf00d") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.sortingDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8f8e2ed3c9d04998abf006"), "Value" : 100 } { "_id" : ObjectId("5c8f8e31d3c9d04998abf007"), "Value" : 1 } { "_id" : ObjectId("5c8f8e34d3c9d04998abf008"), "Value" : 150 } { "_id" : ObjectId("5c8f8e37d3c9d04998abf009"), "Value" : 250 } { "_id" : ObjectId("5c8f8e3bd3c9d04998abf00a"), "Value" : 5 } { "_id" : ObjectId("5c8f8e3ed3c9d04998abf00b"), "Value" : 199 } { "_id" : ObjectId("5c8f8e44d3c9d04998abf00c"), "Value" : 243 } { "_id" : ObjectId("5c8f8e48d3c9d04998abf00d"), "Value" : 290 }
情况1-这是按升序获取结果的查询
> db.sortingDemo.find().sort({Value:1});
以下是输出-
{ "_id" : ObjectId("5c8f8e31d3c9d04998abf007"), "Value" : 1 } { "_id" : ObjectId("5c8f8e3bd3c9d04998abf00a"), "Value" : 5 } { "_id" : ObjectId("5c8f8e2ed3c9d04998abf006"), "Value" : 100 } { "_id" : ObjectId("5c8f8e34d3c9d04998abf008"), "Value" : 150 } { "_id" : ObjectId("5c8f8e3ed3c9d04998abf00b"), "Value" : 199 } { "_id" : ObjectId("5c8f8e44d3c9d04998abf00c"), "Value" : 243 } { "_id" : ObjectId("5c8f8e37d3c9d04998abf009"), "Value" : 250 } { "_id" : ObjectId("5c8f8e48d3c9d04998abf00d"), "Value" : 290 }
情况2-这是按降序获取结果的查询。查询如下-
> db.sortingDemo.find().sort({Value:-1});
以下是输出-
{ "_id" : ObjectId("5c8f8e48d3c9d04998abf00d"), "Value" : 290 } { "_id" : ObjectId("5c8f8e37d3c9d04998abf009"), "Value" : 250 } { "_id" : ObjectId("5c8f8e44d3c9d04998abf00c"), "Value" : 243 } { "_id" : ObjectId("5c8f8e3ed3c9d04998abf00b"), "Value" : 199 } { "_id" : ObjectId("5c8f8e34d3c9d04998abf008"), "Value" : 150 } { "_id" : ObjectId("5c8f8e2ed3c9d04998abf006"), "Value" : 100 } { "_id" : ObjectId("5c8f8e3bd3c9d04998abf00a"), "Value" : 5 } { "_id" : ObjectId("5c8f8e31d3c9d04998abf007"), "Value" : 1 }