如何在 MongoDB 中执行升序排序?


要按升序排序,语法如下 −

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() 方法从集合中显示所有文档。查询如下 −

> 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 }

以下是按升序获取结果的查询

> 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 }

更新日期: 2019 年 7 月 30 日

198 次浏览

开启你的事业

通过完成课程获得认证

开始
广告