skip to Main Content
const search = await searchAgent.aggregate([
    {$match: {id: Number(fid), status: {$regex: status, $options: 'i'}}},
    {$sort: {[order_by]: order == 'desc' ? -1 : 1}},
    {$skip: skip},
    {$limit: pagelimit},
])

Here I need to get the total number of documents matching the query. As I am using the limit I can’t get the total count of documents.

2

Answers


  1. Chosen as BEST ANSWER
    const search = await searchAgent.aggregate([
      { $match: { fid: Number(fid), ...agent_details, } },
      { $facet: {
        data: [{
          $sort: {
            [filter.order_by]: order == 'desc' ? -1 : 1 }
          }, {
            $skip: skip
          }, {
            $limit: pagelimit
          }
        ],
        total: [{$count: "total"}]
      }}
    ])
    

    Here I got the result by using the facet method inside the query. I had given the sort and limit inside the facet method, and given the total count outside the facet. So the limit won't affect getting the total count of documents.


  2. The common approach to solve this is to use the $facet stage, then one pipeline is used to match with the proper skip and limit and one pipeline for the count.
    like so:

    const searchResults = await searchAgent.aggregate([
        {
            $match: {
                id: Number(fid),
                status: {$regex: status, $options: 'i'}
            }
        },
        {
            $facet: {
                results: [
                    {
                        $sort: {
                            [order_by]: order == 'desc' ? -1 : 1
                        }
                    },
                    {
                        $skip: skip
                    },
                    {
                        $limit: pagelimit
                    },
                ],
                count: [
                    {
                        $group: {
                            _id: null,
                            count: {
                                $sum: 1
                            }
                        }
                    }
                ]
            }
        }
    ])
    
    const search = searchResults[0]?.results;
    const searchCount = searchResults[0].count[0].count
    

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search