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()
method的帮助下显示集合中的所有文档。查询如下-
> 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 }
以上是 MongoDB如何在一个集合中订购其文档? 的全部内容, 来源链接: utcz.com/z/316157.html