facet-tutorial
- facet-tutorial
- How to Use Facets with MongoDB Search
- Prerequisites
- Create the MongoDB Search Index for Facet
- Search the Collection
- Continue Learning
- Prerequisites
- Create the MongoDB Search Index for Facet
- Search the Collection
- Continue Learning
- Prerequisites
- Create the MongoDB Search Index for Facet
- Search the Collection
- Continue Learning
- Prerequisites
- Create the MongoDB Search Index for Facet
- Search the Collection
For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset
Available tabs: other tabs: fts-vs, data-explorer, vib, jib, search-meta-pipeline, search-meta-variable, cloud, local, maven bom, gradle bom, maven, gradle -->
How to Use Facets with MongoDB Search
Learn to use facets with MongoDB Search to group search results by string values or by date and numeric range values. Select your deployment type, interface, and language below to view the appropriate tutorial.
This tutorial describes how to create an index with a [facet definition](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-definition on string, date, and numeric fields in the sample_mflix.movies collection. It shows how to run a MongoDB 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 a MongoDB Search index with facet definition on the
genres,released, andyearfields in thesample_mflix.moviescollection. -
Run a MongoDB 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](https://www.mongodb.com/docs/search/about/design-patterns.md#std-label-fts-design-patterns-prereqs, you must have a MongoDB instance running MongoDB 7.0 or later.
Create the MongoDB Search Index for Facet
In this section, you will create a MongoDB 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.
In the sidebar, click Clusters under the Database heading.
The Clusters page displays.
- In Atlas, go to the Search & Vector Search page for your cluster.
You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.
### Search & Vector Search
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Search & Vector Search under the Database heading.
-
If you have no clusters, click Create cluster to create one. To learn more, see [Create an Atlas Infinite or Atlas Core Cluster.](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster.md#std-label-create-new-cluster
-
If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.
The Search & Vector Search page displays.
-
Click Create Search Index.
-
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: Index Name: facet-tutorial; Database and Collection:sample_mflix database; movies collection |
| Configuration Method | For a guided experience, select Visual Editor.To edit the raw index definition, select JSON Editor. |
IMPORTANT: The default index name varies by index type: your MongoDB Search index is named default, your Vector Search index is named vector_index, and your Automated Embedding index is named autoembed_index. 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 a MongoDB Search index that uses [dynamic mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings or [static mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings. To learn more about dynamic and static mappings, see [Dynamic and Static Mappings.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings
The following index definition statically indexes the genres field as token type and dynamically indexes the other fields of [supported types](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-bson-data-chart in each document in the movies collection. You can use the MongoDB Search Visual Editor or the MongoDB Search JSON Editor in the Atlas user interface to create the index.
### Visual Editor
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 | genres |
|---|---|
| Data Type | token |
Click Add, then click Save Changes.
-
Click Create Search Index.
-
Close the You're All Set! Modal Window.
A modal window appears to let you know your index is building. Click the Close button.
- Wait for the index to finish building.
The index should take about one minute to build. While it is building, the Status column reads Build in
Progress. When it is finished building, the Status column reads Active.
Search the Collection
You can use [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in queries that use the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search and [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta stages. In this section, you will connect to your cluster and the run the sample query against the sample_mflix.movies collection using the [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta or [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage to group the genre and year fields into buckets. To optimize performance:
-
Use [
$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta stage if you only need thefacetmetadata. -
Use [
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage if you want to retrieve both the query results and thefacetmetadata. -
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.
In the sidebar, click Clusters under the Database heading.
The Clusters page displays.
- In Atlas, go to the Search & Vector Search page for your cluster.
You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.
### Search & Vector Search
If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.
If it's not already displayed, select your project from the Projects menu in the navigation bar.
In the sidebar, click Search & Vector Search under the Database heading.
-
If you have no clusters, click Create cluster to create one. To learn more, see [Create an Atlas Infinite or Atlas Core Cluster.](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster.md#std-label-create-new-cluster
-
If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.
The Search & Vector Search page displays.
- Go to the Search Tester.
Click the Query button to the right of the index to query.
- View and edit the query syntax.
Click Edit $search Query to view a default query syntax sample in JSON (Javascript Object Notation) format.
- Run a MongoDB 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](https://www.mongodb.com/docs/search/query/operators-collectors/near.md#std-label-near-ref 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 field -
Number of movies in the years 1910 to 1939, inclusive
js
[
{
"$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.
MongoDB Search displays the following results in the page:
js
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
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-1920, inclusive lower bound for the1910bucket and exclusive upper bound for the1920bucket -
1920-1930, inclusive lower bound for the1920bucket and exclusive upper bound for the1930bucket -
1930-1940, inclusive lower bound for the1930bucket and exclusive upper bound for the1940bucket
Continue Learning
You can learn more about the [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in MongoDB Search with the following course or video.
Learn with Courses
To learn more about using facets in MongoDB Search, take Unit 9 of the Intro To MongoDB Course on MongoDB University. The 1.5 hour unit includes an overview of MongoDB Search and lessons on creating MongoDB Search indexes, running [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search queries using compound operators, and grouping results by using facet.
Learn by Watching
Follow along with this video to learn about how you can create and use a numeric and string [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in your query to group results and retrieve a count of the results in the groups.
Duration: 11 Minutes
This tutorial describes how to create an index with a [facet definition](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-definition on string, date, and numeric fields in the sample_mflix.movies collection. It shows how to run a MongoDB 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 a MongoDB Search index with facet definition on the
genres,released, andyearfields in thesample_mflix.moviescollection. -
Run a MongoDB 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](https://www.mongodb.com/docs/search/about/design-patterns.md#std-label-fts-design-patterns-prereqs, you must have a MongoDB instance running MongoDB 7.0 or later.
Create the MongoDB Search Index for Facet
In this section, you will create a MongoDB Search index on the genres, year, and released fields in the sample_mflix.movies collection.
- Connect to your cluster using MongoDB Compass.
Open Compass and connect to your cluster. For detailed instructions, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass
- Specify the database and collection.
On the Database screen, click the name of the database sample_mflix, then click the name of the collection movies.
- Create the MongoDB Search index.
Click the Indexes tab, then select Search Indexes.
Click Create Atlas Search Index to open the index creation dialog box.
Name the index facet-tutorial.
Specify the JSON (Javascript Object Notation) MongoDB Search index definition.
json
{
"mappings": {
"dynamic": true,
"fields": {
"genres": {
"type": "token"
}
}
}
}
Click Create Search Index.
Search the Collection
You can use [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in queries that use the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search and [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta stages. In this section, you will connect to your cluster and the run the sample query against the sample_mflix.movies collection using the [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta or [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage to group the genre and year fields into buckets. To optimize performance:
-
Use [
$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta stage if you only need thefacetmetadata. -
Use [
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage if you want to retrieve both the query results and thefacetmetadata. -
Connect to your cluster in MongoDB Compass.
Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass
- Use the
moviescollection in thesample_mflixdatabase.
On the Database screen, click the sample_mflix database, then click the movies collection.
- Run a MongoDB Search facet query that groups the genre and year fields into buckets.
The query uses the following searchMeta operator clauses:
-
[near](https://www.mongodb.com/docs/search/query/operators-collectors/near.md#std-label-near-ref to search for movies released with a
pivotdistance fromoriginof approximately three months from November 11, 1921 -
facetsto 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 [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta or using [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search with the SEARCH_META aggregation variable.
### $searchMeta
| Pipeline Stage | Query |
|---|---|
$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] | |
| } | |
| } | |
| } | |
| }` |
If you enabled Auto Preview, MongoDB Compass displays the following documents next to the $set pipeline stage:
javascript
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
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-1920, inclusive lower bound for the1910bucket and exclusive upper bound for the1920bucket -
1920-1930, inclusive lower bound for the1920bucket and exclusive upper bound for the1930bucket -
1930-1940, inclusive lower bound for the1930bucket and exclusive upper bound for the1940bucket
Continue Learning
You can learn more about the [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in MongoDB Search with the following course or video.
Learn with Courses
To learn more about using facets in MongoDB Search, take Unit 9 of the Intro To MongoDB Course on MongoDB University. The 1.5 hour unit includes an overview of MongoDB Search and lessons on creating MongoDB Search indexes, running [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search queries using compound operators, and grouping results by using facet.
Learn by Watching
Follow along with this video to learn about how you can create and use a numeric and string [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in your query to group results and retrieve a count of the results in the groups.
Duration: 11 Minutes
This tutorial describes how to create an index with a [facet definition](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-definition on string, date, and numeric fields in the sample_mflix.movies collection. It shows how to run a MongoDB 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 a MongoDB Search index with facet definition on the
genres,released, andyearfields in thesample_mflix.moviescollection. -
Run a MongoDB 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](https://www.mongodb.com/docs/search/about/design-patterns.md#std-label-fts-design-patterns-prereqs, you must have a MongoDB instance running MongoDB 7.0 or later.
Create the MongoDB Search Index for Facet
In this section, you will create a MongoDB Search index on the genres, year, and released fields in the sample_mflix.movies collection.
- Connect to the deployment by using
mongosh.
In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh. For detailed instructions on how to connect, see Connect to a Deployment.
- Switch to the database that contains the collection for which you want to create the index.
shell
use sample_mflix
Output:
shell
switched to db sample_mflix
- Run the
db.collection.createSearchIndex()method to create the index.
shell
db.movies.createSearchIndex(
"facet-tutorial",
{
"mappings": {
"dynamic": true
"fields": {
"genres": {
"type": "token"
}
}
}
}
)
Output:
text
facet-tutorial
Search the Collection
You can use [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in queries that use the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search and [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta stages. In this section, you will connect to your cluster and the run the sample query against the sample_mflix.movies collection using the [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta or [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage to group the genre and year fields into buckets. To optimize performance:
-
Use [
$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta stage if you only need thefacetmetadata. -
Use [
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage if you want to retrieve both the query results and thefacetmetadata. -
Connect to your cluster in
mongosh.
Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell
- Switch to the
sample_mflixdatabase.
Run the following command at [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh prompt:
javascript
use sample_mflix
- Run a MongoDB Search facet query that groups the genre and year fields into buckets.
The sample query uses the following to query the collection:
-
[near](https://www.mongodb.com/docs/search/query/operators-collectors/near.md#std-label-near-ref to search for movies released with a
pivotdistance fromoriginof approximately three months from November 11, 1921 -
facetsto 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](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta or using [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search with the SEARCH_META aggregation variable.
### $searchMeta
```js db.movies.aggregate([ { "$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] } } } } } ])
```
Output:
json
[
{
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') }
]
}
}
}
}
]
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-1920, inclusive lower bound for the1910bucket and exclusive upper bound for the1920bucket -
1920-1930, inclusive lower bound for the1920bucket and exclusive upper bound for the1930bucket -
1930-1940, inclusive lower bound for the1930bucket and exclusive upper bound for the1940bucket
Continue Learning
You can learn more about the [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in MongoDB Search with the following course or video.
Learn with Courses
To learn more about using facets in MongoDB Search, take Unit 9 of the Intro To MongoDB Course on MongoDB University. The 1.5 hour unit includes an overview of MongoDB Search and lessons on creating MongoDB Search indexes, running [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search queries using compound operators, and grouping results by using facet.
Learn by Watching
Follow along with this video to learn about how you can create and use a numeric and string [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in your query to group results and retrieve a count of the results in the groups.
Duration: 11 Minutes
This tutorial describes how to create an index with a [facet definition](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-definition on string, date, and numeric fields in the sample_mflix.movies collection. It shows how to run a MongoDB 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 a MongoDB Search index with facet definition on the
genres,released, andyearfields in thesample_mflix.moviescollection. -
Run a MongoDB 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](https://www.mongodb.com/docs/search/about/design-patterns.md#std-label-fts-design-patterns-prereqs, you must have a MongoDB instance running MongoDB 7.0 or later.
Create the MongoDB Search Index for Facet
In this section, you will create a MongoDB Search index on the genres, year, and released fields in the sample_mflix.movies collection.
- Set up the C project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:
shell
# Create a new directory for the project
mkdir atlas-search-project && cd atlas-search-project
Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.
- Define the index.
Create a create_index.c file in your project directory, and copy and paste the following code into the file.
```c
#include
int main (void) { mongoc_client_t client = NULL; mongoc_collection_t collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true;
mongoc_init();
// Connect to your Atlas deployment
client = mongoc_client_new("<connectionString>");
if (!client) {
fprintf(stderr, "Failed to create a MongoDB client.\n");
ok = false;
goto cleanup;
}
// Access your database and collection
database = mongoc_client_get_database(client, "sample_mflix");
collection = mongoc_database_get_collection(database, "movies");
// Specify the command and the new index
const char *cmd_str = BSON_STR({
"createSearchIndexes" : "movies",
"indexes" : [ {
"name" : "facet-tutorial",
"definition" : {
"mappings": {
"dynamic": true,
"fields": {
"genres" : {
"type": "token"
}
}
}
}
} ]
});
// Convert your command to BSON
if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
fprintf(stderr, "Failed to parse command: %s\n", error.message);
ok = false;
goto cleanup;
}
// Create the MongoDB Search index by running the command
if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message);
ok = false;
goto cleanup;
}
printf ("Index created!\n");
cleanup: mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_database_destroy (database); bson_destroy (&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Set up a CMake application
To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:
txt
cmake_minimum_required(VERSION 3.11)
project(atlas-search-index LANGUAGES C)
add_executable (query.out facet_query.c)
find_package(mongoc <version> REQUIRED)
target_link_libraries(query.out mongoc::mongoc)
The preceding code performs the following actions:
-
Configures a C project.
-
Creates a
index.outexecutable for your application. -
Finds and requires the C driver. Replace the
<version>placeholder with your C driver version facet, such as2.0.0. -
Links the program to the
libmongoclibrary.
Note:
In the sample CMakeLists.txt file, the mongoc::mongoc target points to either the static library or the shared library. The library type depends on which one is available and whichever type the user specifies in the MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE CMake configuration setting. If you don't set this value and both library types are available, mongoc::mongoc uses the static library.
You can use the mongoc::static target to explicitly use the static library or the mongoc::shared target to use the shared library.
- Create the index.
In your terminal, run the following commands to build and run this application:
shell
cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Output:
text
Index created!
Search the Collection
You can use [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref in queries that use the [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search and [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta stages. In this section, you will connect to your cluster and the run the sample query against the sample_mflix.movies collection using the [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta or [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage to group the genre and year fields into buckets. To optimize performance:
-
Use [
$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta stage if you only need thefacetmetadata. -
Use [
$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search stage if you want to retrieve both the query results and thefacetmetadata. -
Create a
facet_query.cfile in your project directory.
Copy and paste the following code into the facet_query.c file.
The sample query uses the following to query the collection:
-
[near](https://www.mongodb.com/docs/search/query/operators-collectors/near.md#std-label-near-ref to search for movies released with a
pivotdistance fromoriginof approximately three months from November 11, 1921 -
facetsto 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](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta or using [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search with the SEARCH_META aggregation variable.
### $searchMeta
```c
#include
int main(int argc, char argv[]) { mongoc_client_t client; mongoc_collection_t collection; mongoc_cursor_t cursor; bson_error_t error; const bson_t doc; bson_t pipeline; char *str;
/* Initialize the MongoDB C Driver */
mongoc_init();
/* Connect to MongoDB */
client = mongoc_client_new("<connection-string>");
if (!client) {
fprintf(stderr, "Failed to parse URI.\n");
return EXIT_FAILURE;
}
/* Get a handle on the collection */
collection = mongoc_client_get_collection(client, "sample_mflix", "movies");
/* Create the $searchMeta stage with facet */
bson_t *search_stage = bson_new();
bson_t search_doc, facet_doc, operator_doc, near_doc, facets_doc;
bson_t genres_facet_doc, year_facet_doc;
bson_t boundaries_array;
/* Build the $searchMeta stage */
BSON_APPEND_DOCUMENT_BEGIN(search_stage, "$searchMeta", &search_doc);
BSON_APPEND_UTF8(&search_doc, "index", "facet-tutorial");
/* Build the facet object */
BSON_APPEND_DOCUMENT_BEGIN(&search_doc, "facet", &facet_doc);
/* Build the operator object with near */
BSON_APPEND_DOCUMENT_BEGIN(&facet_doc, "operator", &operator_doc);
BSON_APPEND_DOCUMENT_BEGIN(&operator_doc, "near", &near_doc);
BSON_APPEND_UTF8(&near_doc, "path", "released");
/* Create a date for November 1, 1921 */
bson_append_date_time(&near_doc, "origin", -1,
(int64_t)(-1520035200000)); /* 1921-11-01 in milliseconds since epoch */
BSON_APPEND_INT64(&near_doc, "pivot", 7776000000);
bson_append_document_end(&operator_doc, &near_doc);
bson_append_document_end(&facet_doc, &operator_doc);
/* Build the facets object */
BSON_APPEND_DOCUMENT_BEGIN(&facet_doc, "facets", &facets_doc);
/* Add genres facet */
BSON_APPEND_DOCUMENT_BEGIN(&facets_doc, "genresFacet", &genres_facet_doc);
BSON_APPEND_UTF8(&genres_facet_doc, "path", "genres");
BSON_APPEND_UTF8(&genres_facet_doc, "type", "string");
bson_append_document_end(&facets_doc, &genres_facet_doc);
/* Add year facet with boundaries */
BSON_APPEND_DOCUMENT_BEGIN(&facets_doc, "yearFacet", &year_facet_doc);
BSON_APPEND_UTF8(&year_facet_doc, "path", "year");
BSON_APPEND_UTF8(&year_facet_doc, "type", "number");
/* Create the boundaries array */
BSON_APPEND_ARRAY_BEGIN(&year_facet_doc, "boundaries", &boundaries_array);
char idx[16];
const char *key;
size_t idx_len;
idx_len = bson_uint32_to_string(0, &key, idx, sizeof idx);
bson_append_int32(&boundaries_array, key, idx_len, 1910);
idx_len = bson_uint32_to_string(1, &key, idx, sizeof idx);
bson_append_int32(&boundaries_array, key, idx_len, 1920);
idx_len = bson_uint32_to_string(2, &key, idx, sizeof idx);
bson_append_int32(&boundaries_array, key, idx_len, 1930);
idx_len = bson_uint32_to_string(3, &key, idx, sizeof idx);
bson_append_int32(&boundaries_array, key, idx_len, 1940);
bson_append_array_end(&year_facet_doc, &boundaries_array);
bson_append_document_end(&facets_doc, &year_facet_doc);
bson_append_document_end(&facet_doc, &facets_doc);
bson_append_document_end(&search_doc, &facet_doc);
bson_append_document_end(search_stage, &search_doc);
/* Create the aggregation pipeline array */
pipeline = bson_new();
/* Add search stage to the pipeline array */
idx_len = bson_uint32_to_string(0, &key, idx, sizeof idx);
bson_append_document(pipeline, key, idx_len, search_stage);
/* Set options (max time 5 seconds = 5000 ms) */
mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new(MONGOC_READ_PRIMARY);
bson_t opts = BSON_INITIALIZER;
bson_append_int32(&opts, "maxTimeMS", -1, 5000);
/* Execute the aggregation */
cursor = mongoc_collection_aggregate(
collection,
MONGOC_QUERY_NONE,
pipeline,
&opts,
read_prefs
);
/* Display the results */
while (mongoc_cursor_next(cursor, &doc)) {
str = bson_as_canonical_extended_json(doc, NULL);
printf("%s\n", str);
bson_free(str);
}
/* Check if the cursor encountered any errors */
if (mongoc_cursor_error(cursor, &error)) {
fprintf(stderr, "Cursor Failure: %s\n", error.message);
return EXIT_FAILURE;
}
/* Clean up */
bson_destroy(search_stage);
bson_destroy(pipeline);
bson_destroy(&opts);
mongoc_read_prefs_destroy(read_prefs);
mongoc_cursor_destroy(cursor);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
mongoc_cleanup();
return EXIT_SUCCESS;
}
```
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 to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
- Set up a CMake application.
To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:
txt
cmake_minimum_required(VERSION 3.11)
project(atlas-search-index LANGUAGES C)
add_executable (query.out facet_query.c)
find_package(mongoc <version> REQUIRED)
target_link_libraries(query.out mongoc::mongoc)
The preceding code performs the following actions:
-
Configures a C project.
-
Creates a
index.outexecutable for your application. -
Finds and requires the C driver. Replace the
<version>placeholder with your C driver version facet, such as2.0.0. -
Links the program to the
(本文超出站点单文档体积上限,已截断)
