Search Fundamentals / Facets

Code Recap: Facets

Define an Atlas Search Index for Facets

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

db.movies.createSearchIndex(
  "genresFacetedIndex",
  {
    mappings: {
      dynamic: false,
      fields: {
        genres: {
          type: "token"
        },
        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 following example, 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
          }
        }
      }
    }
  }
])