Display distinctly ordered MongoDB record with skip and limit?


You can work with aggregate framework and use $sort, $skip and $limit to display distinctly ordered records with skip and also set the limit. Let us first create a collection with documents

> 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")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.orderedDistinctDemo.find().pretty();

This will produce the following output −

{ "_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" }

Here is the query to display distinctly ordered record with skip and limit −

> db.orderedDistinctDemo.aggregate(
...    { $group : { _id : "$Name" }},
...    { $sort : { _id: 1 }},
...    { $skip : 3 },
...    { $limit : 8 }
... );

This will produce the following output −

{ "_id" : "Larry" }
{ "_id" : "Sam" }

Updated on: 30-Jul-2019

641 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements