Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$facetcreates multiple output documents from a single input document -
data pipeline applies
$limitto return only the specified number of documents -
totalCount pipeline uses
$countto 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.
Advertisements
