Docs Menu
Docs Home
/
MongoDB Atlas
/ /

How to Run Atlas Search Queries Against Objects in Arrays

On this page

  • Overview
  • Try it in the Atlas Search Playground
  • Try it on Your Atlas Cluster

This tutorial describes how to index and run Atlas Search queries against fields in documents, or objects, that are inside an array (embeddedDocuments). The page contains instructions for running sample queries using a sample index for a sample collection that we have set up for you in the Atlas Search Playground or that you can load, configure, and run on your Atlas cluster.

The sample collection is named schools and it contains three documents. Each document in the sample collection contains the name and mascot of the school, school teachers' first and last names, the classes that each teacher teaches including the subject name and grade level, and the various clubs for the school students.

The index definition for the collection shows the following:

  • Documents in the arrays at the teachers and teachers.classes paths are indexed as embeddedDocuments, and the fields inside the documents are dynamically indexed.

  • Documents in the arrays at the teachers path are also indexed as the document type to support highlighting, and the fields inside the documents are dynamically indexed.

  • Document in the clubs field is indexed as the document type with dynamic mappings enabled and the arrays of documents in the clubs.sports field are indexed as the embeddedDocuments type with dynamic mappings enabled.

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

  • $search to search the collection.

  • $project to include and exclude fields from the collection, and add a field named score in the results. For queries that enable highlighting, the $project stage also adds a new field called highlights, which contains the highlighting information.

The tutorial demonstrates three different queries.

This query demonstrates a search against a field inside a nested 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 on the last name field.

This query demonstrates a search against a field inside an array of documents that is nested inside a document.

It searches for schools that have sports clubs that offer students an opportunity to play either dodgeball or frisbee at the clubs.sports path.

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

It searches for schools that have a teacher teaching 12th grade science class at the teachers.classes path, preferring schools with teachers with last name Smith who teach that class. It also enables highlighting on the subject field inside the classes array of the documents nested inside the teachers array of documents.

On the Atlas Search Playground, we have set up an embedded documents collection, pre-configured an index for the fields in the collection, and defined a query that you can run against the collection. You can also modify the collection, index, and query in the Atlas Search Playground.

To try this query on the Atlas Search Playground, do the following:

1

Access the nested array query example in the Atlas Search Playground.

2
3

To try this query on the Atlas Search Playground, do the following:

1

Access the nested array with an object example query in the Atlas Search Playground.

2
3

To try this query on the Atlas Search Playground, do the following:

1

Access the nested array within an array example query in the Atlas Search Playground.

2
3

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

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

  2. Set up an Atlas Search index with embeddedDocuments fields configured at the following paths:

    • teachers field

    • teachers.classes field

    • clubs.sports field

  3. Run $search queries that search the embedded documents in the schools collection using the compound operator with the embeddedDocument and text operators.

  4. Run a $searchMeta query against an embedded document field to get a count.

Before you begin, ensure that your Atlas cluster meets the requirements described in the Prerequisites. For this tutorial, you don't need to upload the sample data because you will create a new collection and load the documents that you need to run the queries in this tutorial.

You must begin by creating a collection named schools in an existing or new database on your Atlas 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 the 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
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

Click the Browse Collections button for your cluster.

The Data Explorer displays.

3
  1. Click Create Database to create a new database.

  2. Enter the database name and collection name.

    • In the Database Name field, specify local_school_district.

    • For the Collection Name field, specify schools.

4
  1. Select the schools collection if it's not selected.

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

  3. Click the JSON view ({}) to replace the default document.

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

    {
    "_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."
    }
    ]
    }
    }

In this section, you will create an Atlas Search index for the fields in the embedded documents in the local_school_district.schools collection.

To create an Atlas Search index, you must have Project Data Access Admin or higher access to the project.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
4
  • For a guided experience, select Visual Editor.

  • To edit the raw index definition, select JSON Editor.

5
  1. In the Index Name field, enter embedded-documents-tutorial.

    If you name your index default, you don't need to specify an index parameter in the $search pipeline stage. If you give a custom name to your index, you must specify this name in the index parameter.

  2. In the Database and Collection section, find the local_school_district database, and select the schools collection.

6

To learn more about the index definition, see About the Atlas Search Index.

  1. Click Next.

  2. Click Refine Your Index.

  3. Click Add Field in the Field Mappings section and add the following fields in the Customized Configuration tab by clicking Add after configuring the settings for each field, one at a time, in the Add Field Mapping window.

    Field Name
    Data Type
    Enable Dynamic Mapping
    teachers
    EmbeddedDocuments
    On
    teachers.classes
    EmbeddedDocuments
    On
    teachers
    Document
    On
    teachers.classes
    Document
    On
    teachers.classes.grade
    StringFacet
    N/A
    clubs.sports
    EmbeddedDocuments
    On
  4. Click Add Field Mappings to open the Add Field Mapping window.

  5. Select the following from the dropdown.

  6. Click Add Field Mappings to open the Add Field Mapping window.

  7. Select the following from the dropdown.

  8. Toggle to enable Enable Dynamic Mapping if it isn't already enabled and click Add

  9. Click Save.

  10. Click Save Changes.

  1. Replace the default index definition with the following index definition.

    1{
    2 "mappings": {
    3 "dynamic": true,
    4 "fields": {
    5 "clubs": {
    6 "dynamic": true,
    7 "fields": {
    8 "sports": {
    9 "dynamic": true,
    10 "type": "embeddedDocuments"
    11 }
    12 },
    13 "type": "document"
    14 },
    15 "teachers": [
    16 {
    17 "dynamic": true,
    18 "fields": {
    19 "classes": {
    20 "dynamic": true,
    21 "type": "embeddedDocuments"
    22 }
    23 },
    24 "type": "embeddedDocuments"
    25 },
    26 {
    27 "dynamic": true,
    28 "fields": {
    29 "classes": {
    30 "dynamic": true,
    31 "fields": {
    32 "grade": {
    33 "type": "stringFacet"
    34 }
    35 },
    36 "type": "document"
    37 }
    38 },
    39 "type": "document"
    40 }
    41 ]
    42 }
    43 }
    44}
  2. Click Next.

7

Atlas displays a modal window to let you know your index is building.

8

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.

You can run queries against the embedded document fields. This tutorial uses embeddedDocument and text operators inside the compound operator in the queries.

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


➤ Use the Select your language drop-down menu on this page to set the language of the examples in this section.


1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

Click the Query button to the right of the index to query.

4

Click Edit Query to view a default query syntax sample in JSON format.

5

Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

Note

The Search Tester doesn't support highlighting. So, use mongosh or a MongoDB driver to see highlighting information in the results.

To learn more about this query, see About the Queries.

1[
2 {
3 "$search": {
4 "index": "embedded-documents-tutorial",
5 "embeddedDocument": {
6 "path": "teachers",
7 "operator": {
8 "compound": {
9 "must": [{
10 "text": {
11 "path": "teachers.first",
12 "query": "John"
13 }
14 }],
15 "should":[{
16 "text": {
17 "path": "teachers.last",
18 "query": "Smith"
19 }
20 }]
21 }
22 }
23 }
24 }
25 }
26]
SCORE: 0.7830756902694702 _id: "1"
name: "Evergreen High"
mascot: "Jaguars"
teachers: Array
0: Object
first: "Jane"
last: "Earwhacker"
classes: Array
...
1: Object
first: "John"
last: "Smith"
classes: Array
...
clubs: Object
...
SCORE: 0.468008816242218 _id: "2"
name: "Lincoln High"
mascot: "Sharks"
teachers: Array
0: Object
first: "Jane"
last: "Smith"
classes: Array
...
1: Object
first: "John"
last: "Redman"
classes: Array
...
clubs: Object
...

To learn more about this query, see About the Queries.

1[
2 {
3 "$search": {
4 "index": "embedded-documents-tutorial",
5 "embeddedDocument": {
6 "path": "clubs.sports",
7 "operator": {
8 "queryString": {
9 "defaultPath": "clubs.sports.club_name",
10 "query": "dodgeball OR frisbee"
11 }
12 }
13 }
14 }
15 }
16]
score: 0.633669912815094 _id: 2
name: "Lincoln High"
mascot: "Sharks"
teachers: Array
...
clubs: Object
sports: Array (2)
0: Object
club_name: "dodgeball"
description: "provides students an opportunity
to play dodgeball by throwing balls t…"
1: Object
club_name: "martial arts"
description: "provides students an opportunity to learn self-defense or combat that …"
stem: Array (2)
...
score: 0.481589138507843 _id: 1
name: "Evergreen High"
mascot: "Jaguars"
teachers: Array
...
clubs: Object
sports: Array (2)
0: Object
club_name: "archery"
description: "provides students an opportunity to practice and hone the skill of usi…"
1: Object
club_name: "ultimate frisbee"
description: "provides students an opportunity to play frisbee and learn the basics …"
stem: Array (2)
...

To learn more about this query, see About the Queries.

[
{
$search: {
index: "embedded-documents-tutorial",
"embeddedDocument": {
"path": "teachers",
"operator": {
"compound": {
"must": [{
"embeddedDocument": {
"path": "teachers.classes",
"operator": {
"compound": {
"must": [{
"text": {
"path": "teachers.classes.grade",
"query": "12th"
}
},
{
"text": {
"path": "teachers.classes.subject",
"query": "science"
}
}]
}
}
}
}],
"should": [{
"text": {
"path": "teachers.last",
"query": "smith"
}
}]
}
}
}
}
}
]
SCORE: 0.9415585994720459
name: "Springfield High"
mascot: "Pumas"
teachers: Array
0: Object
first: "Jane"
last: "Smith"
classes: Array
0: Object
subject: "art of science"
grade: "12th"
1: Object
subject: "applied science and practical science"
grade: "9th"
2: Object
subject: "remedial math"
grade: "12th"
3: Object
subject: "science"
grade: "10th"
1: Object
first: "Bob"
last: "Green"
classes: Array
0: Object
subject: "science of art"
grade: "11th"
1: Object
subject: "art art art"
grade: "10th"
clubs: Object
...
SCORE: 0.7779859304428101 _id: "1"
name: "Evergreen High"
mascot: "Jaguars"
teachers: Array
0: Object
first: "Jane"
last: "Earwhacker"
classes: Array
0: Object
subject: "art"
grade: "9th"
1: Object
subject: "science"
grade: "12th"
1: Object
first: "John"
last: "Smith"
classes: Array
0: Object
subject: "math"
grade: "12th"
1: Object
subject: "art"
grade: "10th"
clubs: Object
...
1

Open mongosh in a terminal window and connect to your cluster. For detailed instructions on connecting, see Connect via mongosh.

2

Run the following command at mongosh prompt:

use local_school_district
switched to db local_school_district
3

To learn more about these queries, see About the Queries.

To learn more about this query, see About the Queries.

1db.schools.aggregate({
2 "$search": {
3 "index": "embedded-documents-tutorial",
4 "embeddedDocument": {
5 "path": "teachers",
6 "operator": {
7 "compound": {
8 "must": [{
9 "text": {
10 "path": "teachers.first",
11 "query": "John"
12 }
13 }],
14 "should":[{
15 "text": {
16 "path": "teachers.last",
17 "query": "Smith"
18 }
19 }]
20 }
21 }
22 },
23 "highlight": {
24 "path": "teachers.last"
25 }
26 }
27},
28{
29 "$project": {
30 "_id": 1,
31 "teachers": 1,
32 "score": { $meta: "searchScore" },
33 "highlights": { "$meta": "searchHighlights" }
34 }
35})
1[
2 {
3 _id: 1,
4 teachers: [
5 {
6 first: 'Jane',
7 last: 'Earwhacker',
8 classes: [
9 { subject: 'art', grade: '9th' },
10 { subject: 'science', grade: '12th' }
11 ]
12 },
13 {
14 first: 'John',
15 last: 'Smith',
16 classes: [
17 { subject: 'math', grade: '12th' },
18 { subject: 'art', grade: '10th' }
19 ]
20 }
21 ],
22 score: 0.7830756902694702,
23 highlights: [
24 {
25 score: 1.4921371936798096,
26 path: 'teachers.last',
27 texts: [ { value: 'Smith', type: 'hit' } ]
28 }
29 ]
30 },
31 {
32 _id: 2,
33 teachers: [
34 {
35 first: 'Jane',
36 last: 'Smith',
37 classes: [
38 { subject: 'science', grade: '9th' },
39 { subject: 'math', grade: '12th' }
40 ]
41 },
42 {
43 first: 'John',
44 last: 'Redman',
45 classes: [ { subject: 'art', grade: '12th' } ]
46 }
47 ],
48 score: 0.468008816242218,
49 highlights: [
50 {
51 score: 1.4702850580215454,
52 path: 'teachers.last',
53 texts: [ { value: 'Smith', type: 'hit' } ]
54 }
55 ]
56 }
57]

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.

To learn more about this query, see About the Queries.

1db.schools.aggregate(
2 {
3 "$search": {
4 "index": "embedded-documents-tutorial",
5 "embeddedDocument": {
6 "path": "clubs.sports",
7 "operator": {
8 "queryString": {
9 "defaultPath": "clubs.sports.club_name",
10 "query": "dodgeball OR frisbee"
11 }
12 }
13 }
14 }
15 },
16 {
17 "$project": {
18 "_id": 1,
19 "name": 1,
20 "clubs.sports": 1,
21 "score": { $meta: "searchScore" }
22 }
23 }
24)
1[
2 {
3 _id: 2,
4 name: 'Lincoln High',
5 clubs: {
6 sports: [
7 {
8 club_name: 'dodgeball',
9 description: 'provides students an opportunity to play dodgeball by throwing balls to eliminate the members of the opposing team while avoiding being hit themselves.'
10 },
11 {
12 club_name: 'martial arts',
13 description: 'provides students an opportunity to learn self-defense or combat that utilize physical skill and coordination without weapons.'
14 }
15 ]
16 },
17 score: 0.633669912815094
18 },
19 {
20 _id: 1,
21 name: 'Evergreen High',
22 clubs: {
23 sports: [
24 {
25 club_name: 'archery',
26 description: 'provides students an opportunity to practice and hone the skill of using a bow to shoot arrows in a fun and safe environment.'
27 },
28 {
29 club_name: 'ultimate frisbee',
30 description: 'provides students an opportunity to play frisbee and learn the basics of holding the disc and complete passes.'
31 }
32 ]
33 },
34 score: 0.481589138507843
35 }
36]

The two documents in the results show schools that offer clubs where students could play dodgeball or frisbee.

To learn more about this query, see About the Queries.

1db.schools.aggregate({
2 "$search": {
3 "index": "embedded-documents-tutorial",
4 "embeddedDocument": {
5 "path": "teachers",
6 "operator": {
7 "compound": {
8 "must": [{
9 "embeddedDocument": {
10 "path": "teachers.classes",
11 "operator": {
12 "compound": {
13 "must": [{
14 "text": {
15 "path": "teachers.classes.grade",
16 "query": "12th"
17 }
18 },
19 {
20 "text": {
21 "path": "teachers.classes.subject",
22 "query": "science"
23 }
24 }]
25 }
26 }
27 }
28 }],
29 "should": [{
30 "text": {
31 "path": "teachers.last",
32 "query": "smith"
33 }
34 }]
35 }
36 }
37 },
38 "highlight": {
39 "path": "teachers.classes.subject"
40 }
41 }
42},
43{
44 "$project": {
45 "_id": 1,
46 "teachers": 1,
47 "score": { $meta: "searchScore" },
48 "highlights": { "$meta": "searchHighlights" }
49 }
50})
1[
2 {
3 _id: 0,
4 teachers: [
5 {
6 first: 'Jane',
7 last: 'Smith',
8 classes: [
9 { subject: 'art of science', grade: '12th' },
10 {
11 subject: 'applied science and practical science',
12 grade: '9th'
13 },
14 { subject: 'remedial math', grade: '12th' },
15 { subject: 'science', grade: '10th' }
16 ]
17 },
18 {
19 first: 'Bob',
20 last: 'Green',
21 classes: [
22 { subject: 'science of art', grade: '11th' },
23 { subject: 'art art art', grade: '10th' }
24 ]
25 }
26 ],
27 score: 0.9415585994720459,
28 highlights: [
29 {
30 score: 0.7354040145874023,
31 path: 'teachers.classes.subject',
32 texts: [
33 { value: 'art of ', type: 'text' },
34 { value: 'science', type: 'hit' }
35 ]
36 },
37 {
38 score: 0.7871346473693848,
39 path: 'teachers.classes.subject',
40 texts: [
41 { value: 'applied ', type: 'text' },
42 { value: 'science', type: 'hit' },
43 { value: ' and practical ', type: 'text' },
44 { value: 'science', type: 'hit' }
45 ]
46 },
47 {
48 score: 0.7581484317779541,
49 path: 'teachers.classes.subject',
50 texts: [ { value: 'science', type: 'hit' } ]
51 },
52 {
53 score: 0.7189631462097168,
54 path: 'teachers.classes.subject',
55 texts: [
56 { value: 'science', type: 'hit' },
57 { value: ' of art', type: 'text' }
58 ]
59 }
60 ]
61 },
62 {
63 _id: 1,
64 teachers: [
65 {
66 first: 'Jane',
67 last: 'Earwhacker',
68 classes: [
69 { subject: 'art', grade: '9th' },
70 { subject: 'science', grade: '12th' }
71 ]
72 },
73 {
74 first: 'John',
75 last: 'Smith',
76 classes: [
77 { subject: 'math', grade: '12th' },
78 { subject: 'art', grade: '10th' }
79 ]
80 }
81 ],
82 score: 0.7779859304428101,
83 highlights: [
84 {
85 score: 1.502043604850769,
86 path: 'teachers.classes.subject',
87 texts: [ { value: 'science', type: 'hit' } ]
88 }
89 ]
90 }
91]

The two documents in the results contain teachers who teach 12th grade science. The document with _id: 0 contains a teacher with last name Smith who teaches 12th grade science.

1

Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect via Compass.

2

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

3

To learn more about these queries, see About the Queries.

To learn more about this query, see About the 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 pipeline stage:

1[
2 {
3 _id: 1,
4 teachers: [
5 {
6 first: 'Jane',
7 last: 'Earwhacker',
8 classes: [
9 { subject: 'art', grade: '9th' },
10 { subject: 'science', grade: '12th' }
11 ]
12 },
13 {
14 first: 'John',
15 last: 'Smith',
16 classes: [
17 { subject: 'math', grade: '12th' },
18 { subject: 'art', grade: '10th' }
19 ]
20 }
21 ],
22 score: 0.7830756902694702,
23 highlights: [
24 {
25 score: 1.4921371936798096,
26 path: 'teachers.last',
27 texts: [ { value: 'Smith', type: 'hit' } ]
28 }
29 ]
30 },
31 {
32 _id: 2,
33 teachers: [
34 {
35 first: 'Jane',
36 last: 'Smith',
37 classes: [
38 { subject: 'science', grade: '9th' },
39 { subject: 'math', grade: '12th' }
40 ]
41 },
42 {
43 first: 'John',
44 last: 'Redman',
45 classes: [ { subject: 'art', grade: '12th' } ]
46 }
47 ],
48 score: 0.468008816242218,
49 highlights: [
50 {
51 score: 1.4702850580215454,
52 path: 'teachers.last',
53 texts: [ { value: 'Smith', type: 'hit' } ]
54 }
55 ]
56 }
57]

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.

To learn more about this query, see About the Queries.

Pipeline Stage
Query
$search
{
"index": "embedded-documents-tutorial",
embeddedDocument: {
path: "clubs.sports",
operator: {
queryString: {
defaultPath: "clubs.sports.club_name",
query: "dodgeball OR frisbee",
}
}
}
}
$project
{
"_id": 1,
"name": 1,
"clubs.sports": 1,
"score": { $meta: "searchScore" }
}

If you enabled Auto Preview, MongoDB Compass displays the following documents next to the $project pipeline stage:

1[
2 {
3 _id: 2,
4 name: 'Lincoln High',
5 clubs: {
6 sports: [
7 {
8 club_name: 'dodgeball',
9 description: 'provides students an opportunity to play dodgeball by throwing balls to eliminate the members of the opposing team while avoiding being hit themselves.'
10 },
11 {
12 club_name: 'martial arts',
13 description: 'provides students an opportunity to learn self-defense or combat that utilize physical skill and coordination without weapons.'
14 }
15 ]
16 },
17 score: 0.633669912815094
18 },
19 {
20 _id: 1,
21 name: 'Evergreen High',
22 clubs: {
23 sports: [
24 {
25 club_name: 'archery',
26 description: 'provides students an opportunity to practice and hone the skill of using a bow to shoot arrows in a fun and safe environment.'
27 },
28 {
29 club_name: 'ultimate frisbee',
30 description: 'provides students an opportunity to play frisbee and learn the basics of holding the disc and complete passes.'
31 }
32 ]
33 },
34 score: 0.481589138507843
35 }
36]

The two documents in the results show schools that offer clubs where students could play dodgeball or frisbee.

To learn more about this query, see About the Queries.

Pipeline Stage
Query
$search
{
"index": "embedded-documents-tutorial",
"embeddedDocument": {
"path": "teachers",
"operator": {
"compound": {
"must": [{
"embeddedDocument": {
"path": "teachers.classes",
"operator": {
"compound": {
"must": [{
"text": {
"path": "teachers.classes.grade",
"query": "12th"
}
},
{
"text": {
"path": "teachers.classes.subject",
"query": "science"
}
}]
}
}
}
}],
"should": [{
"text": {
"path": "teachers.last",
"query": "smith"
}
}]
}
}
},
"highlight": {
"path": "teachers.classes.subject"
}
}
$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 pipeline stage:

1[
2 {
3 _id: 0,
4 teachers: [
5 {
6 first: 'Jane',
7 last: 'Smith',
8 classes: [
9 { subject: 'art of science', grade: '12th' },
10 {
11 subject: 'applied science and practical science',
12 grade: '9th'
13 },
14 { subject: 'remedial math', grade: '12th' },
15 { subject: 'science', grade: '10th' }
16 ]
17 },
18 {
19 first: 'Bob',
20 last: 'Green',
21 classes: [
22 { subject: 'science of art', grade: '11th' },
23 { subject: 'art art art', grade: '10th' }
24 ]
25 }
26 ],
27 score: 0.9415585994720459,
28 highlights: [
29 {
30 score: 0.7354040145874023,
31 path: 'teachers.classes.subject',
32 texts: [
33 { value: 'art of ', type: 'text' },
34 { value: 'science', type: 'hit' }
35 ]
36 },
37 {
38 score: 0.7871346473693848,
39 path: 'teachers.classes.subject',
40 texts: [
41 { value: 'applied ', type: 'text' },
42 { value: 'science', type: 'hit' },
43 { value: ' and practical ', type: 'text' },
44 { value: 'science', type: 'hit' }
45 ]
46 },
47 {
48 score: 0.7581484317779541,
49 path: 'teachers.classes.subject',
50 texts: [ { value: 'science', type: 'hit' } ]
51 },
52 {
53 score: 0.7189631462097168,
54 path: 'teachers.classes.subject',
55 texts: [
56 { value: 'science', type: 'hit' },
57 { value: ' of art', type: 'text' }
58 ]
59 }
60 ]
61 },
62 {
63 _id: 1,
64 teachers: [
65 {
66 first: 'Jane',
67 last: 'Earwhacker',
68 classes: [
69 { subject: 'art', grade: '9th' },
70 { subject: 'science', grade: '12th' }
71 ]
72 },
73 {
74 first: 'John',
75 last: 'Smith',
76 classes: [
77 { subject: 'math', grade: '12th' },
78 { subject: 'art', grade: '10th' }
79 ]
80 }
81 ],
82 score: 0.7779859304428101,
83 highlights: [
84 {
85 score: 1.502043604850769,
86 path: 'teachers.classes.subject',
87 texts: [ { value: 'science', type: 'hit' } ]
88 }
89 ]
90 }
91]

The two documents in the results contain teachers who teach 12th grade science. The document with _id: 0 contains a teacher with last name Smith who teaches 12th grade science.

1
  1. Create a new directory called embedded-documents-query and initialize your project with the dotnet new command.

    mkdir embedded-documents-query
    cd embedded-documents-query
    dotnet new console
  2. Add the .NET/C# Driver to your project as a dependency.

    dotnet add package MongoDB.Driver
2

To learn more about these queries, see About the Queries.

To learn more about this query, see About the Queries.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class NestedArrayExample
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our SchoolDocument
14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var districtSchoolsDatabase = mongoClient.GetDatabase("local_school_district");
20 var schoolsCollection = districtSchoolsDatabase.GetCollection<SchoolDocument>("schools");
21
22 // define variables for query
23 var compoundQuery = Builders<TeacherDocument>.Search.Compound()
24 .Must(Builders<TeacherDocument>.Search.Text(teacher => teacher.First, "John"))
25 .Should(Builders<TeacherDocument>.Search.Text(teacher => teacher.Last, "Smith"));
26 var opts = new SearchHighlightOptions<SchoolDocument>(school => school.Teachers.Select(teacher => teacher.Last));;
27
28 // define and run pipeline
29 var results = schoolsCollection.Aggregate()
30 .Search(Builders<SchoolDocument>.Search.EmbeddedDocument(
31 school => school.Teachers, compoundQuery), opts,
32 indexName: "embedded-documents-tutorial"
33 )
34 .Project<SchoolDocument>(Builders<SchoolDocument>.Projection
35 .Include(school => school.Name)
36 .Include(school => school.Mascot)
37 .Include(school => school.Teachers)
38 .MetaSearchScore(school => school.Score)
39 .MetaSearchHighlights("highlights"))
40 .ToList();
41
42 // print results
43 foreach (var school in results)
44 {
45 Console.WriteLine(school.ToJson());
46 }
47 }
48}
49
50[BsonIgnoreExtraElements]
51public class SchoolDocument
52{
53 public int Id { get; set; }
54 public string Name { get; set; }
55 public string Mascot { get; set; }
56 public TeacherDocument[] Teachers { get; set; }
57 [BsonElement("highlights")]
58 public List<SearchHighlight> Highlights { get; set; }
59 public double Score { get; set; }
60}
61
62[BsonIgnoreExtraElements]
63public class TeacherDocument
64{
65 public string First { get; set; }
66 public string Last { get; set; }
67 public ClassDocument[] Classes { get; set; }
68}
69
70[BsonIgnoreExtraElements]
71public class ClassDocument
72{
73 public string Subject { get; set; }
74 public string Grade { get; set; }
75}

To learn more about this query, see About the Queries.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6using System;
7using System.Collections.Generic;
8using System.Reflection.Emit;
9
10public class NestedArrayWithinObjectExample
11{
12 private const string MongoConnectionString = "<connection-string>";
13
14 public static void Main(string[] args)
15 {
16 // allow automapping of the camelCase database fields to our SchoolDocument
17 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
18 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
19
20 // connect to your Atlas cluster
21 var mongoClient = new MongoClient(MongoConnectionString);
22 var districtSchoolsDatabase = mongoClient.GetDatabase("local_school_district");
23 var schoolsCollection = districtSchoolsDatabase.GetCollection<SchoolDocument>("schools");
24
25 // define variables for query
26 var queryStringQuery = Builders<ExtraCurricularDocument>.Search.QueryString(
27 sport => sport.ClubName, "dodgeball OR frisbee"
28 );
29
30 // define and run pipeline
31 var results = schoolsCollection.Aggregate()
32 .Search(Builders<SchoolDocument>.Search.EmbeddedDocument(
33 school => school.Clubs.Sports, queryStringQuery),
34 indexName: "embedded-documents-tutorial"
35 )
36 .Project<SchoolDocument>(Builders<SchoolDocument>.Projection
37 .Include(school => school.Clubs)
38 .Include(school => school.Name)
39 .Include(school => school.Id)
40 .MetaSearchScore(school => school.Score))
41 .ToList();
42
43 // print results
44 foreach (var school in results)
45 {
46 Console.WriteLine(school.ToJson());
47 }
48 }
49}
50
51[BsonIgnoreExtraElements]
52public class SchoolDocument
53{
54 public int Id { get; set; }
55 public string Name { get; set; }
56 public ClubDocument Clubs { get; set; }
57 public double Score { get; set; }
58}
59
60[BsonIgnoreExtraElements]
61public class ClubDocument
62{
63 public ExtraCurricularDocument[] Sports { get; set; }
64}
65
66[BsonIgnoreExtraElements]
67public class ExtraCurricularDocument
68{
69 [BsonElement("club_name")]
70 public string ClubName { get; set; }
71 public string Description { get; set; }
72}

To learn more about this query, see About the Queries.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class NestedArrayWithinArrayExample
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our SchoolDocument
14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var districtSchoolsDatabase = mongoClient.GetDatabase("local_school_district");
20 var schoolsCollection = districtSchoolsDatabase.GetCollection<SchoolDocument>("schools");
21
22 // define variables for query
23 var mustQuery = Builders<ClassDocument>.Search.Compound()
24 .Must(Builders<ClassDocument>.Search.Text(classes => classes.Grade, "12th"), Builders<ClassDocument>.Search.Text(classes => classes.Subject, "science"));
25 var compoundQuery = Builders<TeacherDocument>.Search.Compound()
26 .Must(Builders<TeacherDocument>.Search.EmbeddedDocument(teacher => teacher.Classes, mustQuery))
27 .Should(Builders<TeacherDocument>.Search.Text(teacher => teacher.Last, "smith"));
28 var opts = new SearchHighlightOptions<SchoolDocument>("teachers.classes.subject");
29
30 // define and run pipeline
31 var results = schoolsCollection.Aggregate()
32 .Search(Builders<SchoolDocument>.Search.EmbeddedDocument(
33 school => school.Teachers, compoundQuery), opts,
34 indexName: "embedded-documents-tutorial"
35 )
36 .Project<SchoolDocument>(Builders<SchoolDocument>.Projection
37 .Include(school => school.Teachers)
38 .MetaSearchScore(school => school.Score)
39 .MetaSearchHighlights("highlights"))
40 .ToList();
41
42 // print results
43 foreach (var school in results)
44 {
45 Console.WriteLine(school.ToJson());
46 }
47 }
48}
49
50[BsonIgnoreExtraElements]
51public class SchoolDocument
52{
53 public int Id { get; set; }
54 public TeacherDocument[] Teachers { get; set; }
55 [BsonElement("highlights")]
56 public List<SearchHighlight> Highlights { get; set; }
57 public double Score { get; set; }
58}
59
60[BsonIgnoreExtraElements]
61public class TeacherDocument
62{
63 public string First { get; set; }
64 public string Last { get; set; }
65 public ClassDocument[] Classes { get; set; }
66}
67
68[BsonIgnoreExtraElements]
69public class ClassDocument
70{
71 public string Subject { get; set; }
72 public string Grade { get; set; }
73}
3

Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.

4
dotnet run embedded-documents-query.csproj
{
"_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"
}]
}],
"highlights" : [{
"path" : "teachers.last",
"score" : 1.4921371936798096,
"texts" : [{ "type" : "Hit", "value" : "Smith" }]
}],
"score" : 0.78307569026947021
}
{
"_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"
}]
}],
"highlights" : [{
"path" : "teachers.last",
"score" : 1.4702850580215454,
"texts" : [{ "type" : "Hit", "value" : "Smith" }]
}],
"score" : 0.46800881624221802
}
dotnet run embedded-documents-query.csproj
{
"_id" : 2,
"name" : "Lincoln High",
"clubs" : {
"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."
}]
},
"score" : 0.63366991281509399
}
{
"_id" : 1,
"name" : "Evergreen High",
"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."
}]
},
"score" : 0.48158913850784302
}
dotnet run embedded-documents-query.csproj
{
"_id" : 0,
"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"
}]
}],
"highlights" : [{
"path" : "teachers.classes.subject",
"score" : 0.73540401458740234,
"texts" : [
{ "type" : "Text", "value" : "art of " },
{ "type" : "Hit", "value" : "science" }
]
}, {
"path" : "teachers.classes.subject",
"score" : 0.78713464736938477,
"texts" : [
{ "type" : "Text", "value" : "applied " },
{ "type" : "Hit", "value" : "science" },
{ "type" : "Text", "value" : " and practical " },
{ "type" : "Hit", "value" : "science" }]
}, {
"path" : "teachers.classes.subject",
"score" : 0.7581484317779541,
"texts" : [{ "type" : "Hit", "value" : "science" }]
}, {
"path" : "teachers.classes.subject",
"score" : 0.7189631462097168,
"texts" : [
{ "type" : "Hit", "value" : "science" },
{ "type" : "Text", "value" : " of art" }
]
}],
"score" : 0.9415585994720459
}
{
"_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"
}]
}],
"highlights" : [{
"path" : "teachers.classes.subject",
"score" : 1.502043604850769,
"texts" : [{ "type" : "Hit", "value" : "science" }]
}],
"score" : 0.77798593044281006
}
1
2

To learn more about these queries, see About the Queries.

To learn more about this query, see About the Queries.

1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 // connect to your Atlas cluster
14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19
20 // set namespace
21 collection := client.Database("local_school_district").Collection("schools")
22
23 // define pipeline stages
24 searchStage := bson.D{{"$search", bson.M{
25 "index": "embedded-documents-tutorial",
26 "embeddedDocument": bson.M{
27 "path": "teachers", "operator": bson.M{
28 "compound": bson.M{
29 "must": bson.A{
30 bson.M{
31 "text": bson.D{
32 {"path", "teachers.first"},
33 {"query", "John"},
34 },
35 },
36 },
37 "should": bson.A{
38 bson.M{
39 "text": bson.D{
40 {"path", "teachers.last"},
41 {"query", "Smith"},
42 },
43 },
44 },
45 },
46 },
47 },
48 "highlight": bson.D{{"path", "teachers.last"}},
49 }}}
50
51 projectStage := bson.D{{"$project", bson.D{{"teachers", 1}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}}
52
53 // run pipeline
54 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage})
55 if err != nil {
56 panic(err)
57 }
58
59 // print results
60 var results []bson.D
61 if err = cursor.All(context.TODO(), &results); err != nil {
62 panic(err)
63 }
64 for _, result := range results {
65 fmt.Println(result)
66 }
67}

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.

To learn more about this query, see About the Queries.

1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 // connect to your Atlas cluster
14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19
20 // set namespace
21 collection := client.Database("local_school_district").Collection("schools")
22
23 // define pipeline stages
24 searchStage := bson.D{{"$search", bson.M{
25 "index": "embedded-documents-tutorial",
26 "embeddedDocument": bson.D{
27 {"path", "clubs.sports"},
28 {"operator",
29 bson.D{
30 {"queryString",
31 bson.D{
32 {"defaultPath", "clubs.sports.club_name"},
33 {"query", "dodgeball OR frisbee"},
34 },
35 },
36 },
37 },
38 },
39 }}}
40
41 projectStage := bson.D{{"$project", bson.D{{"name", 1}, {"clubs.sports", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
42
43 // run pipeline
44 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage})
45 if err != nil {
46 panic(err)
47 }
48
49 // print results
50 var results []bson.D
51 if err = cursor.All(context.TODO(), &results); err != nil {
52 panic(err)
53 }
54 for _, result := range results {
55 fmt.Println(result)
56 }
57}

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.

To learn more about this query, see About the Queries.

1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 // connect to your Atlas cluster
14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19
20 // set namespace
21 collection := client.Database("local_school_district").Collection("schools")
22
23 // define pipeline stages
24 searchStage := bson.D{{"$search", bson.M{
25 "index": "embedded-documents-tutorial",
26 "embeddedDocument": bson.M{
27 "path": "teachers",
28 "operator": bson.M{
29 "compound": bson.M{
30 "must": bson.A{
31 bson.M{
32 "embeddedDocument": bson.M{
33 "path": "teachers.classes",
34 "operator": bson.M{
35 "compound": bson.M{
36 "must": bson.A{
37 bson.M{
38 "text": bson.D{
39 {"path", "teachers.classes.grade"},
40 {"query", "12th"},
41 },
42 },
43 bson.M{
44 "text": bson.D{
45 {"path", "teachers.classes.subject"},
46 {"query", "science"},
47 },
48 },
49 },
50 },
51 },
52 },
53 },
54 },
55 "should": bson.A{
56 bson.M{
57 "text": bson.D{
58 {"path", "teachers.last"},
59 {"query", "Smith"},
60 },
61 },
62 },
63 },
64 },
65 },
66 "highlight": bson.D{{"path", "teachers.classes.subject"}},
67 }}}
68
69 projectStage := bson.D{{"$project", bson.D{{"teachers", 1}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}}
70
71 // run pipeline
72 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage})
73 if err != nil {
74 panic(err)
75 }
76
77 // print results
78 var results []bson.D
79 if err = cursor.All(context.TODO(), &results); err != nil {
80 panic(err)
81 }
82 for _, result := range results {
83 fmt.Println(result)
84 }
85}

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.

3
go run basic-embedded-documents-search.go
1[
2 {_id 1}
3 {teachers [[
4 {first Jane}
5 {last Earwhacker}
6 {classes [[{subject art} {grade 9th}] [{subject science} {grade 12th}]]}
7 ] [
8 {first John}
9 {last Smith}
10 {classes [[{subject math} {grade 12th}] [{subject art} {grade 10th}]]}
11 ]]}
12 {score 0.7830756902694702}
13 {highlights [[
14 {score 1.4921371936798096}
15 {path teachers.last}
16 {texts [[{value Smith} {type hit}]]}
17 ]]}
18]
19[
20 {_id 2}
21 {teachers [[
22 {first Jane}
23 {last Smith}
24 {classes [[{subject science} {grade 9th}] [{subject math} {grade 12th}]]}
25 ] [
26 {first John}
27 {last Redman}
28 {classes [[{subject art} {grade 12th}]]}
29 ]]}
30 {score 0.468008816242218}
31 {highlights [[
32 {score 1.4702850580215454}
33 {path teachers.last}
34 {texts [[{value Smith} {type hit}]]}
35 ]]}
36]

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.

go run complex-embedded-documents-search.go
1[
2 {_id 2}
3 {name Lincoln High}
4 {clubs [
5 {sports [
6 [
7 {club_name dodgeball}
8 {description provides students an opportunity to play dodgeball by throwing balls to eliminate the members of the opposing team while avoiding being hit themselves.}
9 ] [
10 {club_name martial arts}
11 {description provides students an opportunity to learn self-defense or combat that utilize physical skill and coordination without weapons.}
12 ]
13 ]}
14 ]}
15 {score 0.633669912815094}
16]
17[
18 {_id 1}
19 {name Evergreen High}
20 {clubs [
21 {sports [
22 [
23 {club_name archery}
24 {description provides students an opportunity to practice and hone the skill of using a bow to shoot arrows in a fun and safe environment.}
25 ] [
26 {club_name ultimate frisbee}
27 {description provides students an opportunity to play frisbee and learn the basics of holding the disc and complete passes.}
28 ]
29 ]}
30 ]}
31 {score 0.481589138507843}
32]

The two documents in the results show schools that offer clubs where students could play dodgeball or frisbee.

go run nested-embedded-documents-search.go
1[
2 {_id 0}
3 {teachers [[
4 {first Jane}
5 {last Smith}
6 {classes [[{subject art of science} {grade 12th}] [{subject applied science and practical science} {grade 9th}] [{subject remedial math} {grade 12th}] [{subject science} {grade 10th}]]}
7 ] [
8 {first Bob}
9 {last Green}
10 {classes [[{subject science of art} {grade 11th}] [{subject art art art} {grade 10th}]]}
11 ]]}
12 {score 0.9415585994720459}
13 {highlights [[
14 {score 0.7354040145874023}
15 {path teachers.classes.subject}
16 {texts [[{value art of } {type text}] [{value science} {type hit}]]}
17 ] [
18 {score 0.7871346473693848}
19 {path teachers.classes.subject}
20 {texts [[{value applied } {type text}] [{value science} {type hit}] [{value and practical } {type text}] [{value science} {type hit}]]}
21 ] [
22 {score 0.7581484317779541}
23 {path teachers.classes.subject}
24 {texts [[{value science} {type hit}]]}
25 ] [
26 {score 0.7189631462097168}
27 {path teachers.classes.subject}
28 {texts [[{value science} {type hit}] [{value of art} {type text}]]}
29 ]]}
30]
31[
32 {_id 1}
33 {teachers [[
34 {first Jane}
35 {last Earwhacker}
36 {classes [[{subject art} {grade 9th}] [{subject science} {grade 12th}]]}
37 ] [
38 {first John}
39 {last Smith}
40 {classes [[{subject math} {grade 12th}] [{subject art} {grade 10th}]]}
41 ]]}
42 {score 0.7779859304428101}
43 {highlights [[
44 {score 1.502043604850769}
45 {path teachers.classes.subject}
46 {texts [[{value science} {type hit}]]}
47 ]]}
48]

The two documents in the results contain teachers who teach 12th grade science. The document with _id: 0 contains a teacher with last name Smith who teaches 12th grade science.

1
junit
4.11 or higher version
mongodb-driver-sync
4.3.0 or higher version
slf4j-log4j12
1.7.30 or higher version
2
3

To learn more about these queries, see About the Queries.

To learn more about this query, see About the Queries.

1import java.util.Arrays;
2import java.util.List;
3
4import static com.mongodb.client.model.Aggregates.limit;
5import static com.mongodb.client.model.Aggregates.project;
6import static com.mongodb.client.model.Projections.*;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class BasicEmbeddedDocumentsSearch {
14 public static void main( String[] args ) {
15 // define clauses
16 List<Document> mustClause =
17 List.of(
18 new Document(
19 "text",
20 new Document("path", "teachers.first")
21 .append("query", "John")));
22 List<Document> shouldClause =
23 List.of(
24 new Document(
25 "text",
26 new Document("path", "teachers.last")
27 .append("query", "Smith")));
28
29 // define query
30 Document agg =
31 new Document("$search", new Document("index", "embedded-documents-tutorial")
32 .append("embeddedDocument",
33 new Document("path", "teachers")
34 .append("operator",
35 new Document("compound",
36 new Document("must", mustClause)
37 .append("should", shouldClause))))
38 .append("highlight", new Document("path", "teachers.last")));
39
40 // specify connection
41 String uri = "<connection-string>";
42
43 // establish connection and set namespace
44 try (MongoClient mongoClient = MongoClients.create(uri)) {
45 MongoDatabase database = mongoClient.getDatabase("local_school_district");
46 MongoCollection<Document> collection = database.getCollection("schools");
47
48 // run query and print results
49 collection.aggregate(Arrays.asList(agg,
50 limit(5),
51 project(Document.parse("{score: {$meta: 'searchScore'}, _id: 0, teachers: 1, highlights: {$meta: 'searchHighlights'}}"))))
52 .forEach(doc -> System.out.println(doc.toJson()));
53 }
54 }
55}

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.

To learn more about this query, see About the Queries.

1import java.util.Arrays;
2import static com.mongodb.client.model.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.computed;
5import static com.mongodb.client.model.Projections.fields;
6import static com.mongodb.client.model.Projections.include;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class ComplexEmbeddedDocumentQuery {
14 public static void main(String[] args) {
15 // connect to your Atlas cluster
16 String uri = "<connection-string>";
17
18 try (MongoClient mongoClient = MongoClients.create(uri)) {
19 // set namespace
20 MongoDatabase database = mongoClient.getDatabase("my_test");
21 MongoCollection<Document> collection = database.getCollection("schools");
22
23 // define pipeline
24 Document agg = new Document("$search",
25 new Document("embeddedDocument",
26 new Document("path", "clubs.sports")
27 .append("operator",
28 new Document("queryString",
29 new Document("defaultPath", "clubs.sports.club_name")
30 .append("query", "dodgeball OR frisbee")))));
31
32 // run pipeline and print results
33 collection.aggregate(Arrays.asList(agg,
34 limit(5),
35 project(fields(
36 include("name", "clubs.sports"),
37 computed("score", new Document("$meta", "searchScore"))))))
38 .forEach(doc -> System.out.println(doc.toJson()));
39 }
40 }
41}

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.

To learn more about this query, see About the Queries.

1import java.util.Arrays;
2import java.util.List;
3
4import static com.mongodb.client.model.Aggregates.limit;
5import static com.mongodb.client.model.Aggregates.project;
6import com.mongodb.client.MongoClient;
7import com.mongodb.client.MongoClients;
8import com.mongodb.client.MongoCollection;
9import com.mongodb.client.MongoDatabase;
10import org.bson.Document;
11
12public class NestedEmbeddedDocumentsSearch {
13 public static void main( String[] args ) {
14 // define clauses
15 List<Document> nestedMustClause =
16 List.of(
17 new Document(
18 "text",
19 new Document("path", "teachers.classes.grade")
20 .append("query", "12th")),
21 new Document("text",
22 new Document("path", "teachers.classes.subject")
23 .append("query", "science")));
24 List<Document> mustClause =
25 List.of(
26 new Document(
27 "embeddedDocument",
28 new Document("path", "teachers.classes")
29 .append("operator", new Document("compound",
30 new Document("must", nestedMustClause)))));
31 List<Document> shouldClause =
32 List.of(
33 new Document(
34 "text",
35 new Document("path", "teachers.last")
36 .append("query", "Smith")));
37
38 // define query
39 Document agg =
40 new Document(
41 "$search",
42 new Document("index", "embedded-documents-tutorial")
43 .append("embeddedDocument",
44 new Document("path", "teachers")
45 .append("operator",
46 new Document("compound",
47 new Document("must", mustClause)
48 .append("should", shouldClause))))
49 .append("highlight", new Document("path", "teachers.classes.subject")));
50
51 // specify connection
52 String uri = "<connection-string>";
53
54 // establish connection and set namespace
55 try (MongoClient mongoClient = MongoClients.create(uri)) {
56 MongoDatabase database = mongoClient.getDatabase("local_school_district");
57 MongoCollection<Document> collection = database.getCollection("schools");
58
59 // run query and print results
60 collection.aggregate(Arrays.asList(agg,
61 limit(5),
62 project(Document.parse("{score: {$meta: 'searchScore'}, _id: 0, teachers: 1, highlights: {$meta: 'searchHighlights'}}"))))
63 .forEach(doc -> System.out.println(doc.toJson()));
64 }
65 }
66}

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.

4
javac BasicEmbeddedDocumentsSearch.java
java BasicEmbeddedDocumentsSearch
1{
2 "teachers": [{
3 "first": "Jane",
4 "last": "Earwhacker",
5 "classes": [{
6 {"subject": "art", "grade": "9th"},
7 {"subject": "science", "grade": "12th"}
8 ]
9 }, {
10 "first": "John",
11 "last": "Smith",
12 "classes": [
13 {"subject": "math", "grade": "12th"},
14 {"subject": "art", "grade": "10th"}
15 ]
16 }],
17 "score": 0.7830756902694702,
18 "highlights": [{
19 "score": 1.4921371936798096,
20 "path": "teachers.last",
21 "texts": [{"value": "Smith", "type": "hit"}]
22 }]
23}
24{
25 "teachers": [{
26 "first": "Jane",
27 "last": "Smith",
28 "classes": [
29 {"subject": "science", "grade": "9th"},
30 {"subject": "math", "grade": "12th"}
31 ]
32 }, {
33 "first": "John",
34 "last": "Redman",
35 "classes": [
36 {"subject": "art", "grade": "12th"}
37 ]
38 }],
39 "score": 0.468008816242218,
40 "highlights": [{
41 "score": 1.4702850580215454,
42 "path": "teachers.last",
43 "texts": [{"value": "Smith", "type": "hit"}]
44 }]
45}

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.

javac ComplexEmbeddedDocumentQuery.java
java ComplexEmbeddedDocumentQuery
1{
2 "_id": 2,
3 "name": "Lincoln High",
4 "clubs": {
5 "sports": [
6 {"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."},
7 {"club_name": "martial arts", "description": "provides students an opportunity to learn self-defense or combat that utilize physical skill and coordination without weapons."}
8 ]
9 },
10 "score": 0.633669912815094
11}
12{
13 "_id": 1,
14 "name": "Evergreen High",
15 "clubs": {
16 "sports": [
17 {"club_name": "arc