您可以使用聚合框架,并使用$sort,$skip和$limit通过skip显示不同顺序的记录,并设置限制。首先让我们创建一个包含文档的集合
> db.orderedDistinctDemo.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccfb8e0140b992277dae0e9") } > db.orderedDistinctDemo.insertOne({"Name":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccfb8e5140b992277dae0ea") } > db.orderedDistinctDemo.insertOne({"Name":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccfb8e7140b992277dae0eb") } > db.orderedDistinctDemo.insertOne({"Name":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccfb8ea140b992277dae0ec") } > db.orderedDistinctDemo.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccfb8ee140b992277dae0ed") } > db.orderedDistinctDemo.insertOne({"Name":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccfb8f2140b992277dae0ee") } > db.orderedDistinctDemo.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccfb8f6140b992277dae0ef") } > db.orderedDistinctDemo.insertOne({"Name":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccfb8f9140b992277dae0f0") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.orderedDistinctDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ccfb8e0140b992277dae0e9"), "Name" : "John" } { "_id" : ObjectId("5ccfb8e5140b992277dae0ea"), "Name" : "Larry" } { "_id" : ObjectId("5ccfb8e7140b992277dae0eb"), "Name" : "Larry" } { "_id" : ObjectId("5ccfb8ea140b992277dae0ec"), "Name" : "Sam" } { "_id" : ObjectId("5ccfb8ee140b992277dae0ed"), "Name" : "John" } { "_id" : ObjectId("5ccfb8f2140b992277dae0ee"), "Name" : "Carol" } { "_id" : ObjectId("5ccfb8f6140b992277dae0ef"), "Name" : "David" } { "_id" : ObjectId("5ccfb8f9140b992277dae0f0"), "Name" : "Carol" }
这是查询来显示具有跳跃和限制的明显排序的记录-
> db.orderedDistinctDemo.aggregate( ... { $group : { _id : "$Name" }}, ... { $sort : { _id: 1 }}, ... { $skip : 3 }, ... { $limit : 8 } ... );
这将产生以下输出-
{ "_id" : "Larry" } { "_id" : "Sam" }