Combine Facet Summaries with Search Results

Saturday, March 11th 2023

Q: Can I send facet summaries along with search results in one aggregation pipeline call?

Yes, you can send facet summaries along with search results in one aggregation pipeline call using the $facet stage. The $facet stage allows you to specify multiple aggregation pipelines, each with its own set of stages, which can be executed in parallel on the same set of input documents.

Here's an example of how you can use $facet to combine search results and facet summaries in a single aggregation pipeline call:

db.collection.aggregate([ { $match: { field1: "value1" } }, // Filter documents { $facet: { // Execute multiple pipelines in parallel searchResults: [ // Pipeline for search results { $skip: 10 }, // Skip first 10 results { $limit: 20 } // Return next 20 results ], facetSummaries: [ // Pipeline for facet summaries { $group: { _id: "$field2", count: { $sum: 1 } } }, // Group by field2 and count documents { $sort: { count: -1 } }, // Sort by count in descending order { $limit: 10 } // Return top 10 facet summaries ] } } ])

In this example, we are using $facet to execute two pipelines in parallel:

  • The searchResults pipeline filters the documents based on field1 and returns a paginated set of search results using the $skip and $limit stages.
  • The facetSummaries pipeline groups the documents by field2 and counts the number of documents in each group using the $group stage. It then sorts the results by count in descending order using the $sort stage and returns the top 10 facet summaries using the $limit stage.

The output of the $facet stage is an array of objects, where each object corresponds to one of the specified pipelines. In this example, the output would contain two objects, one for searchResults and one for facetSummaries, each with its own set of results.

Note that the $facet stage can be used with any set of aggregation pipeline stages, so you can customize the search results and facet summaries to fit your specific needs.