Display distinctly ordered MongoDB record with skip and limit?

To display distinctly ordered MongoDB records with skip and limit, use the aggregation framework combining $group, $sort, $skip, and $limit operations. This approach ensures unique values while maintaining order and pagination control.

Syntax

db.collection.aggregate([
    { $group: { _id: "$fieldName" }},
    { $sort: { _id: 1 }},
    { $skip: numberOfRecordsToSkip },
    { $limit: maxRecordsToReturn }
]);

Sample Data

db.orderedDistinctDemo.insertMany([
    {"Name": "John"},
    {"Name": "Larry"},
    {"Name": "Larry"},
    {"Name": "Sam"},
    {"Name": "John"},
    {"Name": "Carol"},
    {"Name": "David"},
    {"Name": "Carol"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ccfb8e0140b992277dae0e9"),
        ObjectId("5ccfb8e5140b992277dae0ea"),
        ObjectId("5ccfb8e7140b992277dae0eb"),
        ObjectId("5ccfb8ea140b992277dae0ec"),
        ObjectId("5ccfb8ee140b992277dae0ed"),
        ObjectId("5ccfb8f2140b992277dae0ee"),
        ObjectId("5ccfb8f6140b992277dae0ef"),
        ObjectId("5ccfb8f9140b992277dae0f0")
    ]
}

Display all documents to see the original data ?

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

Example: Skip 3 Records and Limit to 8

Display distinct names, skip the first 3 alphabetically sorted names, and limit results to 8 ?

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

How It Works

  • $group: { _id: "$Name" } ? Groups by Name field, creating distinct values
  • $sort: { _id: 1 } ? Sorts distinct names alphabetically (ascending)
  • $skip: 3 ? Skips first 3 records (Carol, David, John)
  • $limit: 8 ? Limits output to maximum 8 records

Conclusion

Use MongoDB's aggregation pipeline to combine distinct grouping with sorting and pagination. The $group stage removes duplicates, while $sort, $skip, and $limit provide ordered pagination control.

Updated on: 2026-03-15T01:00:26+05:30

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements