How to get searched documents with total documents count in Atlas search

Hi, for pagination, when i make search using atlas search with a limit in aggregation, i also need the total count of documents found for my search, my code in nodejs-

assets =  await Asset.aggregate([
            { $search:{

            index: 'assetsSearch',

            text: {

            query: [search_query],

            path: 'name',

            fuzzy: { maxEdits:2, prefixLength:3 }

            }}},

            // If i use the count operator below, i can get the total documents count, but i will 
            be using "$limit" in my real code, so then i won't get total count of the documents 
            for my search.

            {$count: 'totalAssetsCount'}
           ])

please give me solution for it.

Hi @Talib_Azhar ,

I believe you can use a $facet stage after the $search stage.

Here you would have the results in result field with limit stage and the count in the total field with a count stage.

[ { $search : ... } , {$facet : { result : [{$limit ... } ] , total : [{$count ... }]}}]

Thanks
Pavel

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.