Home > Mobile >  Get a count of total documents with MongoDB aggregation when using limit
Get a count of total documents with MongoDB aggregation when using limit

Time:09-20

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.

CodePudding user response:

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

CodePudding user response:


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"}]
                }}
            ])
  • Related