embedded-documents-tutorial

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: basic, complex, advanced, nestedarray, simple, fts-vs, data-explorer, vib, jsonib, cloud, local, maven bom, gradle bom, maven, gradle -->

How to Run MongoDB Search Queries Against Fields in Embedded Documents

This tutorial demonstrates how to index and run MongoDB Search queries against fields that are inside an array of documents, even when the array of documents is nested itself. To enable queries against these fields, you index the document fields as the [embeddedDocuments](https://www.mongodb.com/docs/search/indexes/field-types/embedded-documents-type.md#std-label-bson-data-types-embedded-documents type.

The tutorial on this page demonstrates queries against fields in the following types of arrays:

  • Array of documents.

  • Array of documents inside a document.

  • Array of documents inside an array of documents.

Before you begin, ensure that your cluster meets the requirements described in the [Prerequisites.](https://www.mongodb.com/docs/search/about/design-patterns.md#std-label-fts-design-patterns-prereqs

About this Tutorial

Expand this section to learn more about the sample collection, index, and queries used in this tutorial.

To demonstrate how to run queries against embedded documents, this tutorial walks you through the following steps:

  1. Create a sample collection named schools with embedded documents in your cluster.

  2. Set up a MongoDB Search index with [embeddedDocuments](https://www.mongodb.com/docs/search/indexes/field-types/embedded-documents-type.md#std-label-bson-data-types-embedded-documents fields configured at the following paths:

  3. teachers field

  4. teachers.classes field

  5. clubs.sports field

  6. Run [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search queries that search the embedded documents in the schools collection using the [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref with the [embeddedDocument](https://www.mongodb.com/docs/search/query/operators-collectors/embedded-document.md#std-label-embedded-document-ref and [text.](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref

  7. Run a [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta query against an embedded document field to get a count.

About the Collection

The schools sample collection contains three documents. Each document contains the name and mascot of the school, the``first`` and last name of each teacher, the classes that they teach including the subject and grade, and the various clubs available.

About the Index

The index for this collection specifies the following documents in arrays:

  • Documents in the arrays at the teachers and teachers.classes paths are indexed as [embeddedDocuments](https://www.mongodb.com/docs/search/indexes/field-types/embedded-documents-type.md#std-label-bson-data-types-embedded-documents, and the fields inside the documents are [dynamically](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings indexed.

  • Documents in the arrays at the teachers path are also indexed as the [document](https://www.mongodb.com/docs/search/indexes/field-types/document-type.md#std-label-bson-data-types-document type to support [highlighting](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref, and the fields inside the documents are dynamically indexed.

  • Document in the clubs field is indexed as the [document](https://www.mongodb.com/docs/search/indexes/field-types/document-type.md#std-label-bson-data-types-document type with [dynamic mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-static-dynamic-mappings enabled and the arrays of documents in the clubs.sports field are indexed as the embeddedDocuments type with dynamic mappings enabled.

About the Queries

The sample queries search the embedded documents in the schools collection. The queries use the following pipeline stages:

  • [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search to search the collection.

  • [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project to include and exclude fields from the collection, and add a field named score in the results. For queries that enable [highlighting](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref, the [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage also adds a new field called highlights, which contains the highlighting information.

The tutorials demonstrate the following queries:

Nested Array

This query demonstrates a search against a field inside an array of documents.

It searches at the teachers path for teachers with the first name John and specifies a preference for teachers with the last name Smith. It also enables [highlighting](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref on the last name field.

Note:

The tutorial for [your cluster](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-cluster also includes a [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta query to get a count of the number of schools that offer classes in each grade.

Run Queries Against Embedded Documents

This tutorial demonstrates sample MongoDB Search queries against fields in embedded documents. To learn more about these queries, see [About this Tutorial.](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-details

Create a Sample Collection and Load the Data

You must begin by creating a collection named schools in an existing or new database on your cluster. After creating the collection, you must upload the sample data into your collection. To learn more about the documents in the sample collection, see [About this Tutorial.](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-sample-collection

The steps in this section walk you through creating a new database and collection, and loading the sample data into your collection.

Create and populate the schools collection:

  1. 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

  1. Create the collection.

On the Database screen, create a database named local_school_district, then select Create Collection.

  1. Specify the collection name.

Enter schools as the collection name and select Create Collection.

  1. Load sample data into the collection.

Select the schools collection if it's not already selected.

Click Add Data for each of the sample documents to add to the collection.

Click Insert Document to replace the default document.

Copy and paste the following sample documents, one at a time, and click Insert to add the documents, one at a time, to the collection.

json { "_id": 0, "name": "Springfield High", "mascot": "Pumas", "teachers": [{ "first": "Jane", "last": "Smith", "classes": [{ "subject": "art of science", "grade": "12th" }, { "subject": "applied science and practical science", "grade": "9th" }, { "subject": "remedial math", "grade": "12th" }, { "subject": "science", "grade": "10th" }] }, { "first": "Bob", "last": "Green", "classes": [{ "subject": "science of art", "grade": "11th" }, { "subject": "art art art", "grade": "10th" }] }], "clubs": { "stem": [ { "club_name": "chess", "description": "provides students opportunity to play the board game of chess informally and competitively in tournaments." }, { "club_name": "kaboom chemistry", "description": "provides students opportunity to experiment with chemistry that fizzes and explodes." } ], "arts": [ { "club_name": "anime", "description": "provides students an opportunity to discuss, show, and collaborate on anime and broaden their Japanese cultural understanding." }, { "club_name": "visual arts", "description": "provides students an opportunity to train, experiment, and prepare for internships and jobs as photographers, illustrators, graphic designers, and more." } ] } }

json { "_id": 1, "name": "Evergreen High", "mascot": "Jaguars", "teachers": [{ "first": "Jane", "last": "Earwhacker", "classes": [{ "subject": "art", "grade": "9th" }, { "subject": "science", "grade": "12th" }] }, { "first": "John", "last": "Smith", "classes": [{ "subject": "math", "grade": "12th" }, { "subject": "art", "grade": "10th" }] }], "clubs": { "sports": [ { "club_name": "archery", "description": "provides students an opportunity to practice and hone the skill of using a bow to shoot arrows in a fun and safe environment." }, { "club_name": "ultimate frisbee", "description": "provides students an opportunity to play frisbee and learn the basics of holding the disc and complete passes." } ], "stem": [ { "club_name": "zapped", "description": "provides students an opportunity to make exciting gadgets and explore electricity." }, { "club_name": "loose in the chem lab", "description": "provides students an opportunity to put the scientific method to the test and get elbow deep in chemistry." } ] } }

json { "_id": 2, "name": "Lincoln High", "mascot": "Sharks", "teachers": [{ "first": "Jane", "last": "Smith", "classes": [{ "subject": "science", "grade": "9th" }, { "subject": "math", "grade": "12th" }] }, { "first": "John", "last": "Redman", "classes": [{ "subject": "art", "grade": "12th" }] }], "clubs": { "arts": [ { "club_name": "ceramics", "description": "provides students an opportunity to acquire knowledge of form, volume, and space relationships by constructing hand-built and wheel-thrown forms of clay." }, { "club_name": "digital art", "description": "provides students an opportunity to learn about design for entertainment, 3D animation, technical art, or 3D modeling." } ], "sports": [ { "club_name": "dodgeball", "description": "provides students an opportunity to play dodgeball by throwing balls to eliminate the members of the opposing team while avoiding being hit themselves." }, { "club_name": "martial arts", "description": "provides students an opportunity to learn self-defense or combat that utilize physical skill and coordination without weapons." } ] } }

Create the MongoDB Search Index

  1. 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

  1. Specify the database and collection.

On the Database screen, click the name of the database, then click the name of the collection.

  1. 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, embedded-documents-tutorial.

Specify the JSON (Javascript Object Notation) MongoDB Search index definition.

json { "mappings": { "dynamic": true, "fields": { "clubs": { "dynamic": true, "fields": { "sports": { "dynamic": true, "type": "embeddedDocuments" } }, "type": "document" }, "teachers": [ { "dynamic": true, "fields": { "classes": { "dynamic": true, "type": "embeddedDocuments" } }, "type": "embeddedDocuments" }, { "dynamic": true, "fields": { "classes": { "dynamic": true, "fields": { "grade": { "type": "token" } }, "type": "document" } }, "type": "document" } ] } } }

Click Create Search Index.

Run $search Queries Against Embedded Document Fields

You can run queries against the embedded document fields. This tutorial uses [embeddedDocument](https://www.mongodb.com/docs/search/query/operators-collectors/embedded-document.md#std-label-embedded-document-ref and [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operators inside the [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref operator in the queries.

In this section, you will connect to your cluster and run the sample queries using the operators against the fields in the schools collection.

  1. 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

  1. Use the schools collection in the local_school_district database.

On the Database screen, click the local_school_district database, and then click the schools collection.

  1. Run the following MongoDB Search queries against the schools collection.

To learn more about these queries, see [About this Tutorial.](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-queries

### Nested Array

To learn more about this query, see [About this Tutorial.](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-queries

Pipeline Stage Query
$search `{
“index”: “embedded-documents-tutorial”,
“embeddedDocument”: {
“path”: “teachers”,
“operator”: {
“compound”: {
“must”: [{
“text”: {
“path”: “teachers.first”,
“query”: “John”
}
}],
“should”:[{
“text”: {
“path”: “teachers.last”,
“query”: “Smith”
}
}]
}
}
},
“highlight”: {
“path”: “teachers.last”
}
}`
$project `{
“_id”: 1,
“teachers”: 1,
“score”: { $meta: “searchScore” },
“highlights”: { “$meta”: “searchHighlights” }
}If you enabled Auto Preview, MongoDB Compass displays the following documents next to the [$project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project pipeline stage:

shell [ { _id: 1, teachers: [ { first: 'Jane', last: 'Earwhacker', classes: [ { subject: 'art', grade: '9th' }, { subject: 'science', grade: '12th' } ] }, { first: 'John', last: 'Smith', classes: [ { subject: 'math', grade: '12th' }, { subject: 'art', grade: '10th' } ] } ], score: 0.7830756902694702, highlights: [ { score: 1.4921371936798096, path: 'teachers.last', texts: [ { value: 'Smith', type: 'hit' } ] } ] }, { _id: 2, teachers: [ { first: 'Jane', last: 'Smith', classes: [ { subject: 'science', grade: '9th' }, { subject: 'math', grade: '12th' } ] }, { first: 'John', last: 'Redman', classes: [ { subject: 'art', grade: '12th' } ] } ], score: 0.468008816242218, highlights: [ { score: 1.4702850580215454, path: 'teachers.last', texts: [ { value: 'Smith', type: 'hit' } ] } ] } ]

The two documents in the results contain teachers with the first name John. The document with _id: 1 ranks higher because it contains a teacher with the first name John who also has the last name Smith.

Run $searchMeta Query Against Embedded Document Fields

You can run [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta queries against the embedded document fields. In this section, you will connect to your Atlas cluster and run a sample query using the $searchMeta stage and facet on an embedded document field.

  1. 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

  1. Use the schools collection in the local_school_district database.

On the Database screen, click the local_school_district database, and then click the schools collection.

  1. Run the following MongoDB Search queries against the schools collection.

This query finds the high schools and requests a count of the number of schools that offer classes in each grade.

Pipeline Stage Query
$searchMeta `{
“index”: “embedded-embedded-documents-tutorial”,
“facet”: {
“operator”: {
“text”:{
“path”: “name”,
“query”: “High”
}
},
“facets”: {
“gradeFacet”: {
“type”: “string”,
“path”: “teachers.classes.grade”
}
}
}
}MongoDB Compass displays the following in the results:count: Object
lowerBound: 3
facet: Object
gradeFacet: Object
buckets: Array (4)
0: Object
_id: “12th”
count: 3
1: Object
_id: “9th”
count : 3
2: Object
_id: “10th”
count: 2
3: Object
_id: “11th”
count: 1The results show that3schools offer classes for12thand9thgrades,2schools offer classes for10thgrade, and1school offers classes for11thgrade. When you facet by a field inside an embedded document, the query returns count for the top-level parent document, which is theteachers` field for this query.

Create a Sample Collection and Load the Data

You must begin by creating a collection named schools in an existing or new database on your cluster. After creating the collection, you must upload the sample data into your collection. To learn more about the documents in the sample collection, see [About this Tutorial.](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-sample-collection

The steps in this section walk you through creating a new database and collection, and loading the sample data into your collection.

Create and populate the schools collection:

  1. Connect to the deployment 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.

  1. Switch to the local_school_district database.

shell use local_school_district

Output:

shell switched to db local_school_district

  1. Create the schools collection.

shell db.createCollection("schools")

Output:

shell { "ok" : 1 }

  1. Insert documents into the schools collection.

Insert the following documents that define synonym mappings:

shell db.schools.insertMany([ { "_id": 0, "name": "Springfield High", "mascot": "Pumas", "teachers": [{ "first": "Jane", "last": "Smith", "classes": [{ "subject": "art of science", "grade": "12th" }, { "subject": "applied science and practical science", "grade": "9th" }, { "subject": "remedial math", "grade": "12th" }, { "subject": "science", "grade": "10th" }] }, { "first": "Bob", "last": "Green", "classes": [{ "subject": "science of art", "grade": "11th" }, { "subject": "art art art", "grade": "10th" }] }], "clubs": { "stem": [ { "club_name": "chess", "description": "provides students opportunity to play the board game of chess informally and competitively in tournaments." }, { "club_name": "kaboom chemistry", "description": "provides students opportunity to experiment with chemistry that fizzes and explodes." } ], "arts": [ { "club_name": "anime", "description": "provides students an opportunity to discuss, show, and collaborate on anime and broaden their Japanese cultural understanding." }, { "club_name": "visual arts", "description": "provides students an opportunity to train, experiment, and prepare for internships and jobs as photographers, illustrators, graphic designers, and more." } ] } }, { "_id": 1, "name": "Evergreen High", "mascot": "Jaguars", "teachers": [{ "first": "Jane", "last": "Earwhacker", "classes": [{ "subject": "art", "grade": "9th" }, { "subject": "science", "grade": "12th" }] }, { "first": "John", "last": "Smith", "classes": [{ "subject": "math", "grade": "12th" }, { "subject": "art", "grade": "10th" }] }], "clubs": { "sports": [ { "club_name": "archery", "description": "provides students an opportunity to practice and hone the skill of using a bow to shoot arrows in a fun and safe environment." }, { "club_name": "ultimate frisbee", "description": "provides students an opportunity to play frisbee and learn the basics of holding the disc and complete passes." } ], "stem": [ { "club_name": "zapped", "description": "provides students an opportunity to make exciting gadgets and explore electricity." }, { "club_name": "loose in the chem lab", "description": "provides students an opportunity to put the scientific method to the test and get elbow deep in chemistry." } ] } }, { "_id": 2, "name": "Lincoln High", "mascot": "Sharks", "teachers": [{ "first": "Jane", "last": "Smith", "classes": [{ "subject": "science", "grade": "9th" }, { "subject": "math", "grade": "12th" }] }, { "first": "John", "last": "Redman", "classes": [{ "subject": "art", "grade": "12th" }] }], "clubs": { "arts": [ { "club_name": "ceramics", "description": "provides students an opportunity to acquire knowledge of form, volume, and space relationships by constructing hand-built and wheel-thrown forms of clay." }, { "club_name": "digital art", "description": "provides students an opportunity to learn about design for entertainment, 3D animation, technical art, or 3D modeling." } ], "sports": [ { "club_name": "dodgeball", "description": "provides students an opportunity to play dodgeball by throwing balls to eliminate the members of the opposing team while avoiding being hit themselves." }, { "club_name": "martial arts", "description": "provides students an opportunity to learn self-defense or combat that utilize physical skill and coordination without weapons." } ] } } ])

Output:

shell { "acknowledged" : true, "insertedIds" : [ ObjectId("..."), ObjectId("...") ] }

Create the MongoDB Search Index

  1. 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.

  1. Switch to the database that contains the collection for which you want to create the index.

shell use local_school_district

Output:

shell switched to db local_school_district

  1. Run the db.collection.createSearchIndex() method to create the index.

shell db.schools.createSearchIndex( "embedded-documents-tutorial", { "mappings": { "dynamic": true, "fields": { "clubs": { "dynamic": true, "fields": { "sports": { "dynamic": true, "type": "embeddedDocuments" } }, "type": "document" }, "teachers": [ { "dynamic": true, "fields": { "classes": { "dynamic": true, "type": "embeddedDocuments" } }, "type": "embeddedDocuments" }, { "dynamic": true, "fields": { "classes": { "dynamic": true, "fields": { "grade": { "type": "token" } }, "type": "document" } }, "type": "document" } } ] } } } )

Output:

text embedded-documents-tutorial

Run $search Queries Against Embedded Document Fields

You can run queries against the embedded document fields. This tutorial uses [embeddedDocument](https://www.mongodb.com/docs/search/query/operators-collectors/embedded-document.md#std-label-embedded-document-ref and [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref operators inside the [compound](https://www.mongodb.com/docs/search/query/operators-collectors/compound.md#std-label-compound-ref operator in the queries.

In this section, you will connect to your cluster and run the sample queries using the operators against the fields in the schools collection.

  1. Connect to your cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.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

  1. Use the local_school database.

Run the following command at [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh prompt:

sh use local_school_district

Output:

sh switched to db local_school_district

  1. Run the following MongoDB Search queries against the schools collection.

To learn more about these queries, see [About this Tutorial.](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-queries

### Nested Array

To learn more about this query, see [About this Tutorial.](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-queries

json db.schools.aggregate({ "$search": { "index": "embedded-documents-tutorial", "embeddedDocument": { "path": "teachers", "operator": { "compound": { "must": [{ "text": { "path": "teachers.first", "query": "John" } }], "should":[{ "text": { "path": "teachers.last", "query": "Smith" } }] } } }, "highlight": { "path": "teachers.last" } } }, { "$project": { "_id": 1, "teachers": 1, "score": { $meta: "searchScore" }, "highlights": { "$meta": "searchHighlights" } } })

Output:

sh [ { _id: 1, teachers: [ { first: 'Jane', last: 'Earwhacker', classes: [ { subject: 'art', grade: '9th' }, { subject: 'science', grade: '12th' } ] }, { first: 'John', last: 'Smith', classes: [ { subject: 'math', grade: '12th' }, { subject: 'art', grade: '10th' } ] } ], score: 0.7830756902694702, highlights: [ { score: 1.4921371936798096, path: 'teachers.last', texts: [ { value: 'Smith', type: 'hit' } ] } ] }, { _id: 2, teachers: [ { first: 'Jane', last: 'Smith', classes: [ { subject: 'science', grade: '9th' }, { subject: 'math', grade: '12th' } ] }, { first: 'John', last: 'Redman', classes: [ { subject: 'art', grade: '12th' } ] } ], score: 0.468008816242218, highlights: [ { score: 1.4702850580215454, path: 'teachers.last', texts: [ { value: 'Smith', type: 'hit' } ] } ] } ]

The two documents in the results contain teachers with the first name John. The document with _id: 1 ranks higher because it contains a teacher with the first name John who also has the last name Smith.

Run $searchMeta Query Against Embedded Document Fields

You can run [$searchMeta](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta queries against the embedded document fields. In this section, you will connect to your Atlas cluster and run a sample query using the $searchMeta stage and facet on an embedded document field.

  1. Connect to your cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.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

  1. Use the local_school database.

Run the following command at [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh prompt:

sh use local_school_district

Output:

sh switched to db local_school_district

  1. Run the following MongoDB Search query against the schools collection.

This query finds the high schools and requests a count of the number of schools that offer classes in each grade.

json db.schools.aggregate({ "$searchMeta": { "index": "embedded-documents-tutorial", "facet": { "operator": { "text":{ "path": "name", "query": "High" } }, "facets": { "gradeFacet": { "type": "string", "path": "teachers.classes.grade" } } } } })

Output:

sh [ { count: { lowerBound: Long('3') }, facet: { gradeFacet: { buckets: [ { _id: '12th', count: Long('3') }, { _id: '9th', count: Long('3') }, { _id: '10th', count: Long('2') }, { _id: '11th', count: Long('1') } ] } } } ]

The results show that 3 schools offer classes for 12th and 9th grades, 2 schools offer classes for 10th grade, and 1 school offers classes for 11th grade. When you facet by a field inside an embedded document, the query returns count for the top-level parent document, which is the teachers field for this query.

Create a Sample Collection and Load the Data

You must begin by creating a collection named schools in an existing or new database on your cluster. After creating the collection, you must upload the sample data into your collection. To learn more about the documents in the sample collection, see [About this Tutorial.](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-sample-collection

The steps in this section walk you through creating a new database and collection, and loading the sample data into your collection.

  1. 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.

  1. In Atlas, go to the Data Explorer page for your project.

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 Data Explorer under the Database heading.

The Data Explorer displays.

  1. Create a new collection.

Click Create Database to create a new database.

Enter the database name and collection name.

  • In the Database Name field, specify local_school_district.

  • For the Collection Name field, specify schools.

  • Load the following documents into the collection.

Select the schools collection if it's not selected.

Click Insert Document for each of the sample documents to add to the collection.

Click the JSON (Javascript Object Notation) view ({}) to replace the default document.

Copy and paste the following sample documents, one at a time, and click Insert to add the documents, one at a time, to the collection.

json { "_id": 0, "name": "Springfield High", "mascot": "Pumas", "teachers": [{ "first": "Jane", "last": "Smith", "classes": [{ "subject": "art of science", "grade": "12th" }, { "subject": "applied science and practical science", "grade": "9th" }, { "subject": "remedial math", "grade": "12th" }, { "subject": "science", "grade": "10th" }] }, { "first": "Bob", "last": "Green", "classes": [{ "subject": "science of art", "grade": "11th" }, { "subject": "art art art", "grade": "10th" }] }], "clubs": { "stem": [ { "club_name": "chess", "description": "provides students opportunity to play the board game of chess informally and competitively in tournaments." }, { "club_name": "kaboom chemistry", "description": "provides students opportunity to experiment with chemistry that fizzes and explodes." } ], "arts": [ { "club_name": "anime", "description": "provides students an opportunity to discuss, show, and collaborate on anime and broaden their Japanese cultural understanding." }, { "club_name": "visual arts", "description": "provides students an opportunity to train, experiment, and prepare for internships and jobs as photographers, illustrators, graphic designers, and more." } ] } }

json { "_id": 1, "name": "Evergreen High", "mascot": "Jaguars", "teachers": [{ "first": "Jane", "last": "Earwhacker", "classes": [{ "subject": "art", "grade": "9th" }, { "subject": "science", "grade": "12th" }] }, { "first": "John", "last": "Smith", "classes": [{ "subject": "math", "grade": "12th" }, { "subject": "art", "grade": "10th" }] }], "clubs": { "sports": [ { "club_name": "archery", "description": "provides students an opportunity to practice and hone the skill of using a bow to shoot arrows in a fun and safe environment." }, { "club_name": "ultimate frisbee", "description": "provides students an opportunity to play frisbee and learn the basics of holding the disc and complete passes." } ], "stem": [ { "club_name": "zapped", "description": "provides students an opportunity to make exciting gadgets and explore electricity." }, { "club_name": "loose in the chem lab", "description": "provides students an opportunity to put the scientific method to the test and get elbow deep in chemistry." } ] } }

json { "_id": 2, "name": "Lincoln High", "mascot": "Sharks", "teachers": [{ "first": "Jane", "last": "Smith", "classes": [{ "subject": "science", "grade": "9th" }, { "subject": "math", "grade": "12th" }] }, { "first": "John", "last": "Redman", "classes": [{ "subject": "art", "grade": "12th" }] }], "clubs": { "arts": [ { "club_name": "ceramics", "description": "provides students an opportunity to acquire knowledge of form, volume, and space relationships by constructing hand-built and wheel-thrown forms of clay." }, { "club_name": "digital art", "description": "provides students an opportunity to learn about design for entertainment, 3D animation, technical art, or 3D modeling." } ], "sports": [ { "club_name": "dodgeball", "description": "provides students an opportunity to play dodgeball by throwing balls to eliminate the members of the opposing team while avoiding being hit themselves." }, { "club_name": "martial arts", "description": "provides students an opportunity to learn self-defense or combat that utilize physical skill and coordination without weapons." } ] } }

Create the MongoDB Search Index

Choose your preferred configuration method in the Atlas UI and then select the database and collection.

  1. 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.

  1. 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](https://cloud.mongodb.com/go?l=https%3A%2F%2Fclo

(本文超出站点单文档体积上限,已截断)