It seems challenging to fetch the total count of results along with paginated data in a single query without using aggregation.
Although aggregation can help achieve this, considering your large collection size, it might be better to split the query into two parts. Let's take an example where we have a user
collection with a rating
field containing over 10,000 records:
var finalResult = {};
var query = {
rating: {$gt: 2}
};
// Retrieve the first 50 records of users with a rating greater than 2
var users = db.user.find(query).limit(50).skip(0).toArray();
// Obtain the total count of users with a rating greater than 2
var totalUsers = db.user.count(query);
finalResult.count = totalUsers;
finalResult.data = users;
Your final output could look something like this:
finalResult == {
count: 1150,
data: [/*including 50 users*/]
}
I hope this explanation is clear. Some advanced technologies like Grails internally employ similar methods for pagination.
Alternatively, a more concise approach could be:
var finalResult = {};
var query = {
rating: {$gt: 2}
};
var cursor = db.user.find(query).limit(50).skip(0);
// Fetch the total count of users with a rating greater than 2
// The count() method doesn't consider cursor.skip() and cursor.limit() by default
finalResult.count = cursor.count();;
finalResult.data = cursor.toArray();