Get a count of total documents with MongoDB while using limit?

To get a count of total documents while also limiting the results, use the $facet operator in MongoDB. This allows you to run multiple aggregation pipelines on the same data simultaneously − one for the limited data and another for the total count.

Syntax

db.collection.aggregate([
    {
        $facet: {
            data: [{ $limit: number }],
            totalCount: [{ $count: "total" }]
        }
    }
]);

Sample Data

db.totalDocumentDemo.insertMany([
    {
        "InstructorId": 100,
        "InstructorName": "Larry",
        "InstructorFavouriteSubject": ["Java", "MongoDB", "Python"]
    },
    {
        "InstructorId": 200,
        "InstructorName": "Sam",
        "InstructorFavouriteSubject": ["SQL Server", "C#", "Javascript"]
    }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("5c76e6701e9c5dd6f1f78274"),
        "1": ObjectId("5c76e69c1e9c5dd6f1f78275")
    }
}

Example: Get Limited Data with Total Count

db.totalDocumentDemo.aggregate([
    {
        $facet: {
            data: [{ $limit: 1 }],
            totalCount: [{ $count: "total" }]
        }
    }
]);
{
    "data": [
        {
            "_id": ObjectId("5c76e6701e9c5dd6f1f78274"),
            "InstructorId": 100,
            "InstructorName": "Larry",
            "InstructorFavouriteSubject": [
                "Java",
                "MongoDB",
                "Python"
            ]
        }
    ],
    "totalCount": [
        {
            "total": 2
        }
    ]
}

How It Works

  • $facet creates multiple output documents from a single input document
  • data pipeline applies $limit to return only the specified number of documents
  • totalCount pipeline uses $count to get the total document count
  • Both pipelines run on the same original dataset before any limits are applied

Conclusion

The $facet operator efficiently retrieves both limited results and total count in a single query. This approach is ideal for pagination scenarios where you need to display a subset of data while showing the total available records.

Updated on: 2026-03-14T23:56:52+05:30

813 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements