'How to do faceted search queries with MongoDB

I'm making a search page where people can search for other users and filter the results by various categories (gender, industry, occupation, etc) and I want to be able to show a count next to each facet, like you see on ebay and lots of ecommerce sites.

I've got it semi-working, but the problem is that I'm doing the facet counts after the filtering has already taken place, so if the filter includes industry = "science" (for example), then I don't get a count of all the other industries, I only get the count of the users whose industry is "science".

How can I make sure I get the counts of all the industries if the search query includes filtering by industry?

        {
          $geoNear: {
            near: {
              type: "Point",
              coordinates: [parseFloat(longitude), parseFloat(latitude)],
            },
            distanceField: "dist.calculated",
            maxDistance: Number((maxDistance || 1500) * 1609.34),
            spherical: true,
            query: filters,
          },
        },
        {
          $project: {
            name: 1,
            location: 1,
            gender: 1,
            username: 1,
            dist: 1,
            area: 1,
            industry: 1,
          },
        },
        {
          $facet: {
            paginatedResults: [
              { $skip: parseInt(skip) },
              { $limit: parseInt(limit) },
            ],
            totalCount: [
              {
                $count: "count",
              },
            ],
            industry: [
              { $match: { industry: { $exists: 1 } } },
              {
                $sortByCount: "$industry",
              },
            ],
            gender: [
              { $match: { gender: { $exists: 1 } } },
              {
                $sortByCount: "$gender",
              },
            ],
          },
        },
      ]);```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source