用 skip 和 limit 显示明确排序的 MongoDB 记录?
您可以使用聚合框架,并利用 $sort、$skip 和 $limit 来显示明确排序的记录并跳过记录,还可以设置限制。我们首先使用文档创建一个集合
> 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" }
这是使用 skip 和 limit 显示明确排序的记录的查询 -
> db.orderedDistinctDemo.aggregate( ... { $group : { _id : "$Name" }}, ... { $sort : { _id: 1 }}, ... { $skip : 3 }, ... { $limit : 8 } ... );
这会产生以下输出 -
{ "_id" : "Larry" } { "_id" : "Sam" }
广告