Lesson 6: Creating Search Facets / Learn

Code Summary: Creating Search Facets

Define a Search Index for Facets

The following example creates a search index named genresFacetedIndex, which uses the stringFacet field type on the genres field:

db.movies.createSearchIndex(
    "genresFacetedIndex",
    {
      "mappings": {
        "dynamic": false,
        "fields": {
          "genres": {
            "type": "stringFacet"
          },
          "released": {
            "type": "date"
          }
        }
      }
    }
  )

Create a Facet Using $searchMeta

In the following example, the facet operator is used inside the $searchMeta stage to find movies based on their release date and bucket them by genre.

db.movies.aggregate([
    {
      "$searchMeta": {
        "index": "genresFacetedIndex",
        "facet": {
          "operator": {
            "range": {
                "path": "released",
                "gte": ISODate("2000-01-01T00:00:00.000Z"),
                "lte": ISODate("2000-01-31T00:00:00.000Z")
              },
            },
          "facets": {
            "genresFacet": {
              "type": "string",
              "path": "genres"
            }
          }
        }
      }
    }
  ])

Optionally, we can limit the number of buckets in our search query by using the numBuckets option. In the example below, numBuckets is set to 2:

db.movies.aggregate([
    {
      "$searchMeta": {
        "index": "genresFacetedIndex",
        "facet": {
          "operator": {
            "range": {
                "path": "released",
                "gte": ISODate("2000-01-01T00:00:00.000Z"),
                "lte": ISODate("2000-01-31T00:00:00.000Z")
              },
            },
          "facets": {
            "genresFacet": {
              "type": "string",
              "path": "genres",
              "numBuckets":  2
            }
          }
        }
      }
    }
  ])