MongoDB 如何对一个集合中的文档排序?


MongoDB 通过 $natural 运算符对一个集合中的文档进行排序。它在文档从 find() 获取时按原样存储该文档。默认排序为 $natural。现在我们来看看语法 −

db.yourCollectionName.find().sort({ "$natural": 1 });

为了理解上述语法,我们用文档创建一个集合。创建带文档的集合的查询如下 −

> db.orderDocsDemo.insertOne({"UserScore":87});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9531a316f542d757e2b44b")
}
> db.orderDocsDemo.insertOne({"UserScore":98});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9531a816f542d757e2b44c")
}
> db.orderDocsDemo.insertOne({"UserScore":99});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9531b216f542d757e2b44d")
}
> db.orderDocsDemo.insertOne({"UserScore":67});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9531b716f542d757e2b44e")
}
> db.orderDocsDemo.insertOne({"UserScore":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9531bd16f542d757e2b44f")
}
> db.orderDocsDemo.insertOne({"UserScore":91});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9531c416f542d757e2b450")
}
> db.orderDocsDemo.insertOne({"UserScore":86});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9531c816f542d757e2b451")
}

使用 find() 方法从集合中显示所有文档。查询如下 −

> db.orderDocsDemo.find();

输出如下 −

{ "_id" : ObjectId("5c9531a316f542d757e2b44b"), "UserScore" : 87 }
{ "_id" : ObjectId("5c9531a816f542d757e2b44c"), "UserScore" : 98 }
{ "_id" : ObjectId("5c9531b216f542d757e2b44d"), "UserScore" : 99 }
{ "_id" : ObjectId("5c9531b716f542d757e2b44e"), "UserScore" : 67 }
{ "_id" : ObjectId("5c9531bd16f542d757e2b44f"), "UserScore" : 78 }
{ "_id" : ObjectId("5c9531c416f542d757e2b450"), "UserScore" : 91 }
{ "_id" : ObjectId("5c9531c816f542d757e2b451"), "UserScore" : 86 }

以下是针对一个集合对文档进行排序的查询 −

> db.orderDocsDemo.find().sort({ "$natural": 1 });

输出如下 −

{ "_id" : ObjectId("5c9531a316f542d757e2b44b"), "UserScore" : 87 }
{ "_id" : ObjectId("5c9531a816f542d757e2b44c"), "UserScore" : 98 }
{ "_id" : ObjectId("5c9531b216f542d757e2b44d"), "UserScore" : 99 }
{ "_id" : ObjectId("5c9531b716f542d757e2b44e"), "UserScore" : 67 }
{ "_id" : ObjectId("5c9531bd16f542d757e2b44f"), "UserScore" : 78 }
{ "_id" : ObjectId("5c9531c416f542d757e2b450"), "UserScore" : 91 }
{ "_id" : ObjectId("5c9531c816f542d757e2b451"), "UserScore" : 86 }

看看上面的示例输出,我们按插入方式获取相同的文档。

为了获取已排序的文档,使用以下查询 −

> db.orderDocsDemo.find().sort({ "UserScore": 1 });

输出如下 −

{ "_id" : ObjectId("5c9531b716f542d757e2b44e"), "UserScore" : 67 }
{ "_id" : ObjectId("5c9531bd16f542d757e2b44f"), "UserScore" : 78 }
{ "_id" : ObjectId("5c9531c816f542d757e2b451"), "UserScore" : 86 }
{ "_id" : ObjectId("5c9531a316f542d757e2b44b"), "UserScore" : 87 }
{ "_id" : ObjectId("5c9531c416f542d757e2b450"), "UserScore" : 91 }
{ "_id" : ObjectId("5c9531a816f542d757e2b44c"), "UserScore" : 98 }
{ "_id" : ObjectId("5c9531b216f542d757e2b44d"), "UserScore" : 99 }

更新于: 2019-7-30

56 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始吧
广告