How to Use Facets with Atlas Search
On this page
This tutorial describes how to create an index with a facet
definition on string, date, and numeric fields
in the sample_mflix.movies
collection. It shows how to run an Atlas Search
query against those fields for results grouped by values for the string
field and by ranges for the date and numeric fields, including the
count for each of those groups. It takes you through the following
steps:
Set up an Atlas Search index with facet definition on the
genres
,released
, andyear
fields in thesample_mflix.movies
collection.Run Atlas Search query against the
released
field in thesample_mflix.movies
collection for results grouped by values for thegenres
field and by ranges for theyear
field.
To create an Atlas Search index, you must have Project Data Access Admin
or higher access to the project.
Prerequisites
To complete these tutorials, in addition to the prerequisites listed in the Atlas Search Tutorials page, you must have an Atlas cluster running one of the following versions:
MongoDB 5.0.4+
MongoDB 6.0+
MongoDB 7.0+
Create the Atlas Search Index for Facet
In this section, you will create an Atlas Search index on the genres
,
year
, and released
fields in the sample_mflix.movies
collection.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Start your index configuration.
Make the following selections on the page and then click Next.
Search Type | Select the Atlas Search index type. |
Index Name and Data Source | Specify the following information:
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
Specify an index definition.
You can create an Atlas Search index that uses dynamic mappings or static mappings. To learn more about dynamic and static mappings, see Static and Dynamic Mappings.
The following index definition statically indexes the genres
field as
stringFacet
type and dynamically indexes the other fields of
supported types in each document in the movies
collection. You can use the Atlas Search Visual Editor or the
Atlas Search JSON Editor in the Atlas user interface to create the
index.
Click Next, then click Review Your Index.
Click Add Field Mapping under Field Mappings section.
Click Customzed COnfiguration and select the following from the dropdowns:
Field Name
genres
Data Type
StringFacet
Click Add, then click Save Changes.
Click Next.
Review the index definition.
Your index definition should look similar to the following:
{ "mappings": { "dynamic": true, "fields": { "genres": { "type": "stringFacet" } } } } Click Next.
Search the Collection
➤ Use the Select your language drop-down menu to set the language of the examples in this section.
You can use facet in queries that use the
$search
and $searchMeta
stages. In this
section, connect to your Atlas cluster and the run the sample query
against the sample_mflix.movies
collection using the
$searchMeta
or $search
stage to group the
genre
and year
fields into buckets. To optimize performance:
Use
$searchMeta
stage if you only need thefacet
metadata.Use
$search
stage if you want to retrieve both the query results and thefacet
metadata.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Run an Atlas Search query against the indexed field.
To run the query, copy and paste the following query into the the Query Editor, then click Search.
The following query searches for movies released near November 11, 1921. It specifies a pivot
distance
from origin
of approximately three months. It requests
metadata on the genres
and year
field. The query requests
a count of the:
Number of movies in each genre in the
genres
string array fieldNumber of movies in the years 1910 to 1939, inclusive
[ { "$searchMeta": { "index": "facet-tutorial", "facet": { "operator": { "near": { "path": "released", "origin": ISODate("1921-11-01T00:00:00.000+00:00"), "pivot": 7776000000 } }, "facets": { "genresFacet": { "type": "string", "path": "genres" }, "yearFacet" : { "type" : "number", "path" : "year", "boundaries" : [1910,1920,1930,1940] } } } } } ]
Expand your query results.
The Search Tester might not display all the values for the fields in the results. To view all the values for the fields in the results, expand the fields.
Atlas Search displays the following results in the page:
count: Object lowerBound: 20878 facet: Object genresFacet: Object buckets: Array (10) 0: Object _id: "Drama" count: 12149 1: Object _id: "Comedy" count: 6436 2: Object _id: "Romance" count: 3274 3: Object _id: "Crime" count: 2429 4: Object _id: "Thriller" count: 2400 5: Object _id: "Action" count: 2349 6: Object _id: "Adventure" count: 1876 7: Object _id: "Documentary" count: 1755 8: Object _id: "Horror" count: 1432 9: Object _id: "Biography" count: 1244 yearFacet: Object buckets: Array (3) 0: Object _id: 1910 count: 14 1: Object _id: 1920 count: 47 2: Object _id: 1930 count: 238
Connect to your cluster in mongosh
.
Open mongosh
in a terminal window and
connect to your cluster. For detailed instructions on connecting,
see Connect via mongosh
.
Use the sample_mflix
database.
Run the following command at mongosh
prompt:
use sample_mflix
Run an Atlas Search facet query that groups the genre and year fields into buckets.
The sample query uses the following to query the collection:
near to search for movies released with a
pivot
distance fromorigin
of approximately three months from November 11, 1921facets
to request the number of movies in each genre in thegenres
string array field and the number of movies in the years 1910 to 1939, inclusive
You can run this query using $searchMeta
or using
$search
with the SEARCH_META
aggregation variable.
Connect to your cluster in MongoDB Compass.
Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect via Compass.
Run an Atlas Search facet query that groups the genre and year fields into buckets.
The query uses the following searchMeta
operator clauses:
near to search for movies released with a
pivot
distance fromorigin
of approximately three months from November 11, 1921facets
to request the number of movies in each genre in thegenres
string array field and the number of movies in the years 1910 to 1939, inclusive
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
You can run this query using
$searchMeta
or using$search
with theSEARCH_META
aggregation variable.
If you enabled Auto Preview, MongoDB Compass displays the
following documents next to the $set
pipeline stage:
count: Object lowerBound: 20878 facet: Object genresFacet: Object buckets: Array (10) 0: Object _id: "Drama" count: 12149 1: Object _id: "Comedy" count: 6436 2: Object _id: "Romance" count: 3274 3: Object _id: "Crime" count: 2429 4: Object _id: "Thriller" count: 2400 5: Object _id: "Action" count: 2349 6: Object _id: "Adventure" count: 1876 7: Object _id: "Documentary" count: 1755 8: Object _id: "Horror" count: 1432 9: Object _id: "Biography" count: 1244 yearFacet: Object buckets: Array (3) 0: Object _id: 1910 count: 14 1: Object _id: 1920 count: 47 2: Object _id: 1930 count: 238
Set up and initialize the .NET/C# project for the query.
Create a new directory called
facet-query-example
and initialize your project with thedotnet new
command.mkdir facet-query-example cd facet-query-example dotnet new console Add the .NET/C# Driver to your project as a dependency.
dotnet add package MongoDB.Driver
Create the query in the Program.cs
file.
Replace the contents of the
Program.cs
file with the following code.The sample query uses the following to query the collection:
near to search for movies released with a
pivot
distance fromorigin
of approximately three months from November 11, 1921facets
to request the number of movies in each genre in thegenres
string array field and the number of movies in the years 1910 to 1939, inclusive
You can run this query using
$searchMeta
or using$search
with theSEARCH_META
aggregation variable.Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.
Compile and run the Program.cs
file.
dotnet run facet-query-example.csproj
{ "meta" : { "count" : { "lowerBound" : 20878 }, "facet" : { "genresFacet" : { "buckets" : [ { "_id" : "Drama", "count" : 12149 }, { "_id" : "Comedy", "count" : 6436 }, { "_id" : "Romance", "count" : 3274 }, { "_id" : "Crime", "count" : 2429 }, { "_id" : "Thriller", "count" : 2400 }, { "_id" : "Action", "count" : 2349 }, { "_id" : "Adventure", "count" : 1876 }, { "_id" : "Documentary", "count" : 1755 }, { "_id" : "Horror", "count" : 1432 }, { "_id" : "Biography", "count" : 1244 } ] }, "yearFacet" : { "buckets" : [ { "_id" : 1910, "count" : 14 }, { "_id" : 1920, "count" : 47 }, { "_id" : 1930, "count" : 238 } ] } } } }
Run an Atlas Search facet query that groups the genre and year fields into buckets.
Create a file named
facet-query.go
.Copy and paste the following code into the
facet-query.go
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following searchMeta clauses to query the collection:
near to search for movies released with a
pivot
distance fromorigin
of approximately three months from November 11, 1921facets
to request the number of movies in each genre in thegenres
string array field and the number of movies in the years 1910 to 1939, inclusive
Iterates over the cursor to print the documents that match the query.
You can run this query using
$searchMeta
or using$search
with theSEARCH_META
aggregation variable.Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
go run facet-query.go [ {count [ {lowerBound 20878} ]} {facet [ {genresFacet [ {buckets [ [{_id Drama} {count 12149}] [{_id Comedy} {count 6436}] [{_id Romance} {count 3274}] [{_id Crime} {count 2429}] [{_id Thriller} {count 2400}] [{_id Action} {count 2349}] [{_id Adventure} {count 1876}] [{_id Documentary} {count 1755}] [{_id Horror} {count 1432}] [{_id Biography} {count 1244}] ]} ]} {yearFacet [ {buckets [ [{_id 1910} {count 14}] [{_id 1920} {count 47}] [{_id 1930} {count 238}] ]} ]} ]} ]
Run an Atlas Search facet query that groups the genre and year fields into buckets.
Create a file named
FacetQuery.java
.Copy and paste the following code into the
FacetQuery.java
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following searchMeta clauses to query the collection:
near to search for movies released with a
pivot
distance fromorigin
of approximately three months from November 11, 1921facets
to request the number of movies in each genre in thegenres
string array field and the number of movies in the years 1910 to 1939, inclusive
Iterates over the cursor to print the documents that match the query.
You can run this query using
$searchMeta
or using$search
with theSEARCH_META
aggregation variable.Note
To run the sample code in your Maven environment, add the following above the import statements in your file.
package com.mongodb.drivers; Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Compile and run
FacetQuery.java
file.javac FacetQuery.java java FacetQuery {meta: { count: { lowerBound: Long('20878') }, facet: { genresFacet: { buckets: [ { _id: 'Drama', count: Long('12149') }, { _id: 'Comedy', count: Long('6436') }, { _id: 'Romance', count: Long('3274') }, { _id: 'Crime', count: Long('2429') }, { _id: 'Thriller', count: Long('2400') }, { _id: 'Action', count: Long('2349') }, { _id: 'Adventure', count: Long('1876') }, { _id: 'Documentary', count: Long('1755') }, { _id: 'Horror', count: Long('1432') }, { _id: 'Biography', count: Long('1244') } ] }, yearFacet: { buckets: [ { _id: 1910, count: Long('14') }, { _id: 1920, count: Long('47') }, { _id: 1930, count: Long('238') } ] } } }}
Run an Atlas Search facet query that groups the genre and year fields into buckets.
Create a file named
FacetQuery.kt
.Copy and paste the following code into the
FacetQuery.kt
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following to query the collection:
near to search for movies released with a
pivot
distance fromorigin
of approximately three months from November 11, 1921facets
to request the number of movies in each genre in thegenres
string array field and the number of movies in the years 1910 to 1939, inclusive
Prints the documents that match the query from the
AggregateFlow
instance.
You can run this query using
$searchMeta
or using$search
with theSEARCH_META
aggregation variable.Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the
FacetQuery.kt
file.When you run the
FacetQuery.kt
program in your IDE, it prints the following result:Document{{ count=Document{{lowerBound=20878}}, facet=Document{{ genresFacet=Document{{ buckets=[ Document{{_id=Drama, count=12149}}, Document{{_id=Comedy, count=6436}}, Document{{_id=Romance, count=3274}}, Document{{_id=Crime, count=2429}}, Document{{_id=Thriller, count=2400}}, Document{{_id=Action, count=2349}}, Document{{_id=Adventure, count=1876}}, Document{{_id=Documentary, count=1755}}, Document{{_id=Horror, count=1432}}, Document{{_id=Biography, count=1244}} ] }}, yearFacet=Document{{ buckets=[ Document{{_id=1910, count=14}}, Document{{_id=1920, count=47}}, Document{{_id=1930, count=238}} ] }} }} }}
Run an Atlas Search facet query that groups the genre and year fields into buckets.
Create a file named
facet-query.js
.Copy and paste the following code into the
facet-query.js
file.The code example performs the following tasks:
Imports
mongodb
, MongoDB's Node.js driver.Creates an instance of the
MongoClient
class to establish a connection to your Atlas cluster.Uses the following searchMeta clauses to query the collection:
near to search for movies released with a
pivot
distance fromorigin
of approximately three months from November 11, 1921facets
to request the number of movies in each genre in thegenres
string array field and the number of movies in the years 1910 to 1939, inclusive
Iterates over the cursor to print the documents that match the query.
You can run this query using
$searchMeta
or using$search
with theSEARCH_META
aggregation variable.Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
node facet-query.js '{ "meta":{ "count":{"lowerBound":20878}, "facet":{ "genresFacet":{ "buckets":[ {"_id":"Drama","count":12149}, {"_id":"Comedy","count":6436}, {"_id":"Romance","count":3274}, {"_id":"Crime","count":2429}, {"_id":"Thriller","count":2400}, {"_id":"Action","count":2349}, {"_id":"Adventure","count":1876}, {"_id":"Documentary","count":1755}, {"_id":"Horror","count":1432}, {"_id":"Biography","count":1244} ] }, "yearFacet":{ "buckets":[ {"_id":1910,"count":14}, {"_id":1920,"count":47}, {"_id":1930,"count":238} ] } } } }'
Run an Atlas Search facet query that groups the genre and year fields into buckets.
Create a file named
facet-query.py
.touch facet-query.py Copy and paste the following code into the
facet-query.py
file.The following code example:
Imports
pymongo
, MongoDB's Python driver, and thedns
module, which is required to connectpymongo
toAtlas
using a DNS seed list connection string.Creates an instance of the
MongoClient
class to establish a connection to your Atlas cluster.Uses the following to query the collection:
near to search for movies released with a
pivot
distance fromorigin
of approximately three months from November 11, 1921facets
to request the number of movies in each genre in thegenres
string array field and the number of movies in the years 1910 to 1939, inclusive
Iterates over the cursor to print the documents that match the query.
You can run this query using
$searchMeta
or using$search
with theSEARCH_META
aggregation variable.Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
python facet-query.py { 'meta': { 'count': {'lowerBound': 20878}, 'facet': { 'genresFacet': { 'buckets': [ {'_id': 'Drama', 'count': 12149}, {'_id': 'Comedy', 'count': 6436}, {'_id': 'Romance', 'count': 3274}, {'_id': 'Crime', 'count': 2429}, {'_id': 'Thriller', 'count': 2400}, {'_id': 'Action', 'count': 2349}, {'_id': 'Adventure', 'count': 1876}, {'_id': 'Documentary', 'count': 1755}, {'_id': 'Horror', 'count': 1432}, {'_id': 'Biography', 'count': 1244} ] }, 'yearFacet': { 'buckets': [ {'_id': 1910, 'count': 14}, {'_id': 1920, 'count': 47}, {'_id': 1930, 'count': 238} ] } } } }
The results show metadata results for two types of facet search. The
genresFacet
document shows the number of movies in each genre and
the yearFacet
document shows a count of the number of movies
within the boundaries:
1910
, inclusive lower bound the1910
bucket1920
, exclusive upper bound for the1910
bucket and inclusive lower bound for the1920
bucket1930
, exclusive upper bound for the1920
bucket and inclusive lower bound for the1930
bucket
Continue Learning
You can learn more about facet in Atlas Search with our course or video.
Learn with Courses
To learn more about using facets in Atlas Search, take Unit 9 of the
Intro To MongoDB Course on MongoDB University. The 1.5 hour unit includes an overview
of Atlas Search and lessons on creating Atlas Search indexes, running
$search
queries using compound operators,
and grouping results using facet
.
Learn with Videos
Follow along with this video to learn about how you can create and use a numeric and string facet in your query to group results and retrieve a count of the results in the groups.
Duration: 11 Minutes