如何在 MongoDB 中使用自定义字段对带分页的索引和排序进行索引和排序?


首先,让我们使用文档创建一个集合 −

> db.demo373.createIndex({"Name":1,"CountryName":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo373.insertOne({"Name":"Chris","Age":22,"CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e59ffde2ae06a1609a00aff")
}
> db.demo373.insertOne({"Name":"David","Age":21,"CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e59ffe82ae06a1609a00b00")
}
> db.demo373.insertOne({"Name":"Bob","Age":23,"CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e59fff42ae06a1609a00b01")
}
> db.demo373.insertOne({"Name":"John","Age":21,"CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e59ffff2ae06a1609a00b02")
}
> db.demo373.insertOne({"Name":"Carol","Age":23,"CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a00082ae06a1609a00b03")
}

借助 find() 方法从集合中显示所有文档 −

> db.demo373.find();

这将生成以下输出 −

{ "_id" : ObjectId("5e59ffde2ae06a1609a00aff"), "Name" : "Chris", "Age" : 22, "CountryName" : "US" }
{ "_id" : ObjectId("5e59ffe82ae06a1609a00b00"), "Name" : "David", "Age" : 21, "CountryName" : "AUS" }
{ "_id" : ObjectId("5e59fff42ae06a1609a00b01"), "Name" : "Bob", "Age" : 23, "CountryName" : "UK" }
{ "_id" : ObjectId("5e59ffff2ae06a1609a00b02"), "Name" : "John", "Age" : 21, "CountryName" : "US" }
{ "_id" : ObjectId("5e5a00082ae06a1609a00b03"), "Name" : "Carol", "Age" : 23, "CountryName" : "AUS" }

以下是 MongoDB 中使用分页实现索引和排序的查询 −

> db.demo373.find().sort({"Name":1, "Age":1}).limit(4).skip(2);

这将生成以下输出 −

{ "_id" : ObjectId("5e59ffde2ae06a1609a00aff"), "Name" : "Chris", "Age" : 22, "CountryName" : "US" }
{ "_id" : ObjectId("5e59ffe82ae06a1609a00b00"), "Name" : "David", "Age" : 21, "CountryName" : "AUS" }
{ "_id" : ObjectId("5e59ffff2ae06a1609a00b02"), "Name" : "John", "Age" : 21, "CountryName" : "US" }

更新于: 02-Apr-2020

339 次浏览

开启你的 职业 生涯

通过完成本课程获取认证

开始
广告