Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total count along with Mongoose Query skip & limt

I have a json data which contains many objects. I want to limit the data for pagination and I need the total items count. Please help.

Model.find().skip((pageNumber-1)*limit).limit(limit).exec()

I want the count and skipped data in response.

like image 821
govind Avatar asked Jan 22 '16 11:01

govind


People also ask

What is skip in mongoose?

In Mongoose, the skip() method is used to specify the number of documents to skip. When a query is made and the query result is returned, the skip() method will skip the first n documents specified and return the remaining.

How do you count in mongoose?

Mongoose | countDocuments() Function The countDocuments() function is used to count the number of documents that match the filter in a database collection.

Can I use $in in mongoose?

We can specify as many conditions in the query field. But in cases, where we need to filter according to only one field but more than on values. For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator.

Can mongoose queries be chained?

Mongoose lets you structure queries using chaining or, equivalently, using POJOs in a single function call. Model.


2 Answers

I have solved it with $facet and aggregate the following way in mongoose v3+:

const [{ paginatedResult, [{ totalCount }] }] = await Model.aggregate([{
  $facet: {
    paginatedResult: [
      { $match: query },
      { $skip: skip },
      { $limit: limit }
    ],
    totalCount: [
      { $match: query },
      { $count: 'totalCount' }
    ]
  }
}])

where the totalCount refers the total number of records matching the search query while the paginatedResult is only the paginated slice of them.

like image 114
gazdagergo Avatar answered Oct 11 '22 07:10

gazdagergo


The problem with these solutions is that for every request you are doing two queries. This becomes problematic when you have a complex data structure and large data set as performance becomes an issue. Consider instead creating a special function that listens for the /resource?count=true or /resource/count GET methods and returns only the count.

like image 25
Pbrain19 Avatar answered Oct 11 '22 08:10

Pbrain19