Search results and facets in one aggregation


Is it possible to run a search query and get the matching documents and facets from $searchMeta in the same query?

I tried using both $search and searchMeta in the same aggregation pipeline, but that gives an error.

Using $search and $facet.meta = [{ $replaceWith: "$$SEARCH_META" }] only gives the total matching documents, but not facets, i.e. fields indexed with stringFacet.

With ElasticSearch, the matched documents, facets and meta information are returned in the same response. I.e.

{"docs": [...], "meta": {"count": 500, "facets": {...}}}

Can I do this with Atlas Search? :slight_smile:

@Viktor_Frede_Andersen Welcome to the MongoDB Developer Forum.

Here is one example of how to get result documents and facets with a single query:

var query = db.movies.aggregate([
      $search: {
        index: "default",
        facet: {
          operator: {
            text: {
              path: "plot",
              query: "evil"
          facets: {
            ratingsFacet: {
              type: "string",
              path: "rated"
      $facet: {
        results: [{ $limit: 10 }, { $project: { title: 1} }],
        counts: [{ $limit: 1}, { $project: { meta: "$$SEARCH_META"}}]

This works! Thank you. This means I can probably ditch Elastic and use Mongo for both search and database.

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