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, andyearfields in thesample_mflix.moviescollection.Run Atlas Search query against the
releasedfield in thesample_mflix.moviescollection for results grouped by values for thegenresfield and by ranges for theyearfield.
Prerequisites
To complete these tutorials, in addition to the prerequisites listed in the Prerequisites, you must have an Atlas cluster running one of the following versions:
MongoDB 7.0+
MongoDB 8.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.
WARNING: Navigation Improvements In Progress We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview documentation.
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. |
Note
Your Atlas Search index is named default by default. If you keep this name, then your index will be the
default Search index for any Atlas Search query that does not specify a different index option in
its operators. If you are creating multiple indexes, we recommend
that you maintain a consistent, descriptive naming convention across your indexes.
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
token 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 Customized Configuration and select the following from the dropdowns:
Field Name
genresData Type
tokenClick 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": "token" } } } } 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 Collector 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
$searchMetastage if you only need thefacetmetadata.Use
$searchstage if you want to retrieve both the query results and thefacetmetadata.
In Atlas, go to the Clusters page for your project.
WARNING: Navigation Improvements In Progress We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview documentation.
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
genresstring 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.
Switch to 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
pivotdistance fromoriginof approximately three months from November 11, 1921facetsto request the number of movies in each genre in thegenresstring 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
pivotdistance fromoriginof approximately three months from November 11, 1921facetsto request the number of movies in each genre in thegenresstring 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
$searchMetaor using$searchwith theSEARCH_METAaggregation variable.If you enabled Auto Preview, MongoDB Compass displays the following documents next to the
$setpipeline 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-exampleand initialize your project with thedotnet newcommand.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.csfile with the following code.The sample query uses the following to query the collection:
near to search for movies released with a
pivotdistance fromoriginof approximately three months from November 11, 1921facetsto request the number of movies in each genre in thegenresstring array field and the number of movies in the years 1910 to 1939, inclusive
You can run this query using
$searchMetaor using$searchwith theSEARCH_METAaggregation 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 } ] } } } }
...
Copy and paste the following code into the facet-query.go file.
The code example performs the following tasks:
Imports
mongodbpackages 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
pivotdistance fromoriginof approximately three months from November 11, 1921facetsto request the number of movies in each genre in thegenresstring 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 the SEARCH_META aggregation variable.
Replace the connection string and save the file.
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 an Atlas Search facet query that groups the genre and year fields into buckets.
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}] ]} ]} ]} ]
...
Set up the file to run Atlas Search facet query.
Create a file named
FacetQuery.java.Copy and paste the following code into the
FacetQuery.javafile.The code example performs the following tasks:
Imports
mongodbpackages 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
pivotdistance fromoriginof approximately three months from November 11, 1921facetsto request the number of movies in each genre in thegenresstring 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
$searchMetaor using$searchwith theSEARCH_METAaggregation 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') } ] } } }}
...
Set up the file to run an Atlas Search facet query.
Create a file named
FacetQuery.kt.Copy and paste the following code into the
FacetQuery.ktfile.The code example performs the following tasks:
Imports
mongodbpackages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following to query the collection:
near to search for movies released with a
pivotdistance fromoriginof approximately three months from November 11, 1921facetsto request the number of movies in each genre in thegenresstring array field and the number of movies in the years 1910 to 1939, inclusive
Prints the documents that match the query from the
AggregateFlowinstance.
You can run this query using
$searchMetaor using$searchwith theSEARCH_METAaggregation 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}} ] }} }} }}
Set up the file to run an Atlas Search facet query.
Create a file named
facet-query.js.Copy and paste the following code into the
facet-query.jsfile.The code example performs the following tasks:
Imports
mongodb, MongoDB's Node.js driver.Creates an instance of the
MongoClientclass 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
pivotdistance fromoriginof approximately three months from November 11, 1921facetsto request the number of movies in each genre in thegenresstring 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
$searchMetaor using$searchwith theSEARCH_METAaggregation 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 Atlas Search facet query.
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} ] } } } }'
...
Set up the file to run an Atlas Search facet query."
Create a file named
facet-query.py.touch facet-query.py Copy and paste the following code into the
facet-query.pyfile.The following code example:
Imports
pymongo, MongoDB's Python driver, and thednsmodule, which is required to connectpymongotoAtlasusing a DNS seed list connection string.Creates an instance of the
MongoClientclass to establish a connection to your Atlas cluster.Uses the following to query the collection:
near to search for movies released with a
pivotdistance fromoriginof approximately three months from November 11, 1921facetsto request the number of movies in each genre in thegenresstring 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
$searchMetaor using$searchwith theSEARCH_METAaggregation 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 fts| facet query that groups the genre and year fields into buckets.
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 the1910bucket1920, exclusive upper bound for the1910bucket and inclusive lower bound for the1920bucket1930, exclusive upper bound for the1920bucket and inclusive lower bound for the1930bucket
Continue Learning
You can learn more about facet Collector 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 by Watching
Follow along with this video to learn about how you can create and use a
numeric and string facet Collector in your query to group results
and retrieve a count of the results in the groups.
Duration: 11 Minutes