embedded-documents-type

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: nested-array, nested-within-array, vib, jsonib, jib, cloud, local, maven bom, gradle bom, maven, gradle -->

How to Index Fields in Arrays of Objects and Documents

You can use the MongoDB Search embeddedDocuments type to index fields in documents and objects that are elements of an array. MongoDB Search indexes embedded documents independent of their parent document. Each indexed document contains only fields that are part of the embedded document array element.

To query fields indexed within an embeddedDocuments mapping, you must do one of the following:

  • Use the [embeddedDocument](https://www.mongodb.com/docs/search/query/operators-collectors/embedded-document.md#std-label-embedded-document-ref operator with the path specified as the embeddedDocuments field.

  • Use storedSource index option and specify the embeddedDocuments field in the returnScope query option.

You can also [configure dynamic mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-configure-dynamic-mappings to automatically index fields that are part of the embedded document array element.

Considerations

Facet on Embedded Documents

You can facet on date, numeric, and string fields within embeddedDocuments type field to retrieve facet counts based on the number of matching embeddedDocuments elements. To do this, you must:

  1. Configure storedSource to store embeddedDocuments type fields.

  2. Set the query option returnScope.path as the embeddedDocuments field. To learn more about the syntax and usage of returnScope, see [Query, Filter, and Retrieve Arrays of Objects.](https://www.mongodb.com/docs/search/query/return-scope.md#std-label-fts-return-scope

To facet on fields within objects in arrays based on the number of matching root documents, index the path as a document type.

Stored Source for Embedded Documents

You can use the [storedSource](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition option to store and return fields inside an embeddedDocuments type. You can configure all or a subset of the fields to store or exclude from storage at each level of nesting. This allows you to return only the objects within the array that match the query criteria, rather than the entire root document. To learn more about the syntax for storedSource, see [Define Stored Source Fields in Your MongoDB Search Index.](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition

To return the stored field:

  • Specify returnScope.path option as the embeddedDocuments type field. To learn more, see [Query, Filter, and Retrieve Arrays of Objects.](https://www.mongodb.com/docs/search/query/return-scope.md#std-label-fts-return-scope

  • Set returnStoredSource to true to retrieve only the stored fields instead of entire documents from the collection. To learn more, see [Return Stored Source Fields.](https://www.mongodb.com/docs/search/query/return-stored-source.md#std-label-fts-return-stored-source-option

You can't include embeddedDocuments fields that were specified as storedSource.exclude at a higher-level.

embeddedDocuments Type Limitations

The following limitations apply when indexing with the embeddedDocument type:

  • You can use embeddedDocuments only on fields with up to 5 levels of nesting. An embeddedDocuments field can't have more than 4 parent embeddedDocuments fields.

  • You can't define a field inside the embeddedDocuments type as the deprecated [knnVector](https://www.mongodb.com/docs/search/indexes/field-types/knn-vector.md#std-label-fts-data-types-knn-vector type.

  • For [highlighting](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref fields within embedded documents, you must also index the parent of the field that you want to highlight as the [document](https://www.mongodb.com/docs/search/indexes/field-types/document-type.md#std-label-bson-data-types-document type.

  • The following operations require you to also index the parents of the embedded document child field as the [document](https://www.mongodb.com/docs/search/indexes/field-types/document-type.md#std-label-bson-data-types-document type:

  • [Facet](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref on fields within objects in arrays based on the number of matching root documents.

  • [Highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref fields within embedded documents. For an example, see the [How to Run MongoDB Search Queries Against Fields in Embedded Documents](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial tutorial.

  • [Sort](https://www.mongodb.com/docs/search/query/sort.md#std-label-sort-ref the parent documents by a nested field. You must also index the fields that you want to use for sorting.

2,100,000,000 Index Objects Limit

MongoDB Search stops replicating changes for indexes larger than 2,100,000,000 index objects per partition, on a replica set or single shard, where each indexed embedded parent document counts as a single object. Surpassing this limit may result in stale query results.

Using the embeddedDocuments field type can result in indexing objects over this index size limit, because each indexed embedded document is counted as a single object. If you create a MongoDB Search index that has or will soon have more than 2.1 billion index objects, use the [numPartitions](https://www.mongodb.com/docs/search/indexes/index-partition.md#std-label-fts-index-partition index option to partition your index (supported only on Search Nodes deployments) or [shard your cluster.](https://www.mongodb.com/docs/atlas/cluster-additional-settings.md#std-label-create-cluster-sharding

The exact number of index objects can vary based on the rate of document changes and deletions. The [Search Max Number of Lucene Docs](https://www.mongodb.com/docs/atlas/review-atlas-search-metrics.md#std-label-review-atlas-search-metrics metric shows the largest number of Lucene documents in a single partition of any search index within a replica set or shard.

For example, suppose the metric displays “1,500,000,000.” The index with the highest number of Lucene documents in a single partition has about 1,500,000,000 documents in that partition. If the index uses many partitions, it can contain more documents overall.

You can approximate the expected number of index objects in a single index by doing the following steps:

  1. Calculate the number of index objects per document. For every level of nesting, each embedded document counts as a separate index object.

shell number of index objects in document = 1 + number of nested embedded documents

  1. Multiply the number of index objects per document by the total number of documents in the collection

shell total number of index objects = number of index objects in document x total number of documents in collection

Note that this approximation is a lower bound.

Example:

Consider the collection named schools, described in this [tutorial](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-sample-collection, and suppose the collection contains 1000 documents similar to the following:

{
  "_id": 0,
  "name": "Springfield High",
  "mascot": "Pumas",
  "teachers": [
    {
      "first": "Jane",
      "last": "Smith",
      "classes": [
        {
          "subject": "art of science",
          "grade": "12th"
        },
        ... // 2 more embedded documents
      ]
    },
    ... // 1 more embedded document
  ],
  "clubs": {
    "stem": [
      {
        "club_name": "chess",
        "description": "provides students opportunity to play the board game of chess informally and competitively in tournaments."
      },
      ... // 1 more embedded document
    ],
    ... // 1 more embedded document
  }
}

Now consider the index definition for the following fields in the schools collection:

Nested Array

The array of documents named teachers is indexed as the embeddedDocuments type with dynamic mappings enabled. However, the classes field isn't indexed. Use the following to calculate the index objects:

  1. Calculate the number of index objects per document.

shell Number of ``teachers`` embedded documents = up to 2 Total number of index objects per document = 1 + 2 = 3

  1. Multiply by the total number of documents in the collection.

shell Number of documents in the collection = 1000 Number of index objects per document = 3 Total number of index objects for collection = 1000 x 3 = 3000

If your collection has large arrays that might generate 2,100,000,000 index objects, you must [shard](https://www.mongodb.com/docs/atlas/cluster-additional-settings.md#std-label-create-cluster-sharding any clusters that contain indexes with the embeddedDocuments type.

Define the Index for the embeddedDocuments Type

  1. Retrieve your Service Account access token for the project.

Use your service account to generate an access token, which authenticates your requests to the Atlas Administration API. To learn how to generate an access token, see [Make an API (Application Programming Interface) Request.](https://www.mongodb.com/docs/atlas/configure-api-access.md#std-label-example-api-request

  1. Make an API (Application Programming Interface) call.

Replace the following values in the curl command below. This command sends a POST request to your cluster to create a MongoDB Search index with the embeddedDocuments field type.

  • Replace {ACCESS-TOKEN} with the output from the preceding step

  • Replace {groupId} with the project ID of the project where you want to create the MongoDB Search index

  • Replace {clusterName} with the name of the cluster where you want to create the MongoDB Search index

shell curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \ --header "Accept: application/vnd.atlas.2025-03-12+json" \ --header "Content-Type: application/json" \ -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \ -d '{ "collectionName": "<collection>", "database": "<database>", "name": "default", "type": "search", "definition": { "mappings": { "dynamic": <true|false> | { "typeset" : "<type-set-name>" }, "fields": { "<field-name>": { "type": "embeddedDocuments", "dynamic": <true|false> | { "typeSet": "<type-set-name>" }, "fields": { "<field-name>": { <field-mapping-definition> } }, "storedSource": <true|false> | { "include" | "exclude": [ "<field-name>", ... ] } }, ... } }, "typeSets": [ { "name": "<type-set-name>", "types": [ { "type": "<field-type>", ... }, ... ] }, ... ] } }'

Configure embeddedDocuments Field Properties

The MongoDB Search embeddedDocuments type takes the following parameters:

Field Type Necessity Description Default
type String Required Human-readable label that identifies the field type. Value must be embeddedDocuments.
dynamic Boolean or Object Optional Flag that specifies whether to dynamically index using default type set or object that references the name of the configured typeSet that contains the list of field types to dynamically index. Value must be one of the following: boolean - set to true to recursively index all indexable field types or set to false to not dynamically index any of the dynamically indexable field types. For the list of field types that MongoDB Search dynamically indexes using the default type set, see [Enable Default typeSet.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-enable-dynamic-mappings; object - specify the name typeSets that contains the list of field types to index. To learn more, see dynamic.typeSet. If you set this to false, you must specify individual fields to index using fields object. You can also configure individual fields to index separately using the fields object. false
dynamic.typeSet String Optional Name of the typeSet array of objects that configures the field types to index. To learn more, see [Configure a typeSet.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-configure-dynamic-mappings
fields Object Optional Fields to index. This is required if dynamic is false. If dynamic is true, MongoDB Search indexes all indexable field types. You can also independently index individual fields using fields. MongoDB Search doesn't support indexing facet fields as part of an embeddedDocuments field. {}
storedSource Boolean or [Stored Source Definition](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition Optional Specifies fields in the documents to store for query-time look-ups using the [returnedStoredSource](https://www.mongodb.com/docs/search/query/return-stored-source.md#std-label-fts-return-stored-source-option option. You can store fields of all [MongoDB Search Field Types](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-bson-data-chart on MongoDB Search. Value can be one of the following: true, to store all fields; false, to not store any fields; [Object](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-document that specifies the fields to include or exclude from storage If omitted, defaults to false. To learn more, see [Define Stored Source Fields in Your MongoDB Search Index.](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition false
typeSets Array of Objects Optional Field types to index automatically using dynamic mappings. To learn about the field types that you can configure for dynamic mappings, see [Configure a typeSet.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-configure-dynamic-mappings
typeSets.[n].name String Required Human-readable label that identifies the configuration for the fields types to dynamically index.
typeSets.[n].types Array of Objects Required Field types, one per object, to index automatically using dynamic mappings.
typeSets.[n].types.[n].type String Required Field type to automatically index. You can also configure the settings for each field type. If you don't configure any settings, MongoDB Search uses the default values for the field type. To learn more about the field types that you can configure for dynamic mapping, see [Configure a typeSet.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-configure-dynamic-mappings

Try an Example for the embeddedDocuments Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets. After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data, you can use these examples to index fields as the embeddedDocuments type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api.

Basic Example

Automatically index all dynamically indexable fields inside the array of objects.

The following index definition for the sample_training.companies namespace indexes the array of objects in the products field. It also configures MongoDB Search to automatically index all dynamically indexable fields inside the objects in the products array.

curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "companies",
        "database": "sample_training",
        "name": "default",
        "type": "search",
        "definition": {
            "mappings": {
              "dynamic": false,
              "fields": {
                "products": {
                  "type": "embeddedDocuments",
                  "dynamic": true
                }
              }
            }
        }
    }'

Dynamic Index Example

Combine dynamic mappings with static mappings to index nested fields as different field types.

Enable Dynamic Indexing

The following index definition for the sample_training.companies namespace configures MongoDB Search to automatically index all dynamically indexable fields inside the objects in the products array. It also configures the category_code field to be indexed as the [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token type, which is not included in the default type set for dynamic mappings, to support MongoDB Search [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref queries against that field.

curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "companies",
        "database": "sample_training",
        "name": "default",
        "type": "search",
        "definition": {
            "mappings": {
              "dynamic": true,
              "fields": {
                "products": {
                  "dynamic": true,
                  "type": "embeddedDocuments"
                },
                "category_code": {
                  "type": "token"
                }
              }
            }
        }
    }'

Configure Dynamic Indexing

The following index example disables dynamic mappings at the root level and uses static mappings to index the relationships field as the embeddedDocuments type. It also applies the configured stringBooleanIndex typeSet to index only the string and boolean types the relationships array of objects. It applies the stringBooleanIndex typeSet to the nested person document to index only the boolean and string types in the person document.

Note:

To configure typeSet using the Atlas Administration API for dynamic mappings, you must use API (Application Programming Interface) version 2025-09-10 or higher.

curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "companies",
        "database": "sample_training",
        "name": "default",
        "type": "search",
        "definition": {
          "mappings": {
            "dynamic": false,
            "fields": {
              "relationships": {
                "type": "embeddedDocuments",
                "dynamic": {
                  "typeSet": "stringBooleanIndex"
                },
                "fields": {
                  "person": {
                    "type": "document",
                    "dynamic": {
                      "typeSet": "stringBooleanIndex"
                    }
                  }
                }
              }
            }
          },
          "typeSets": [
            {
              "name": "stringBooleanIndex",
              "types": [
                {
                  "type": "boolean"
                },
                {
                  "type": "string"
                }
              ]
            }
          ]
        }'

Specified Fields Example

Index only specific fields in the array of objects.

The following index definition for the sample_training.companies namespace configures MongoDB Search to index only the country_code and state_code fields as the MongoDB Search string type in the offices array of objects.

curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "companies",
        "database": "sample_training",
        "name": "default",
        "type": "search",
        "definition": {
            "mappings": {
              "fields": {
                "offices": {
                  "type": "embeddedDocuments",
                  "dynamic": false,
                  "fields": {
                    "country_code": {
                      "type": "string"
                    },
                    "state_code": {
                      "type": "string"
                    }
                  }
                }
              }
            }
        }
    }'

Stored Source Examples

Use storedSource to configure storage for nested fields in the array of objects for query and retrieval.

Use Relative Path for Stored Source

The following index definition automatically indexes all the fields in the funding_rounds array of objects for querying. It also uses the storedSource field to store the round_code, raised_currency_code, and raised_amount fields on mongot. This allows you to query these stored fields using any operator that supports queries against these field types and retrieve these stored fields inside the parent object (funding_rounds) as individual documents. For a sample query that demonstrates this, see the [range (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-ref [Embedded Documents Example](https://www.mongodb.com/docs/search/query/operators-collectors/range.md#std-label-range-embedded-documents-eg. To query and retrieve other fields in the parent object (funding_rounds), you must use the embeddedDocument operator.

curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "companies",
        "database": "sample_training",
        "name": "default",
        "type": "search",
        "definition": {
          "mappings": {
            "dynamic": false,
            "fields": {
              "funding_rounds": {
                "type": "embeddedDocuments",
                "dynamic": true,
                "storedSource": {
                  "include": ["round_code", "raised_currency_code", "raised_amount"]
                }
              }
            }
          }
        }
    }'

Configure Multiple Stored Source

The following index definition indexes all fields in the the products array of objects. It stores the name field independently for querying the name field and the products array of objects. You can use any operator that supports queries against the field types in the products array of objects to query and retrieve the stored fields as individual documents.

curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
    --header "Accept: application/vnd.atlas.2025-03-12+json" \
    --header "Content-Type: application/json" \
    -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
    -d '{ "collectionName": "companies",
        "database": "sample_training",
        "name": "default",
        "type": "search",
        "definition": {
            "mappings": {
              "dynamic": false,
              "fields": {
                "products": {
                  "type": "embeddedDocuments",
                  "dynamic": true,
                  "storedSource": true
                }
              }
            },
            "storedSource": {
              "include": [ "_id", "name" ]
            }
        }
    }'

You can use the MongoDB Search embeddedDocuments type to index fields in documents and objects that are elements of an array. MongoDB Search indexes embedded documents independent of their parent document. Each indexed document contains only fields that are part of the embedded document array element.

To query fields indexed within an embeddedDocuments mapping, you must do one of the following:

  • Use the [embeddedDocument](https://www.mongodb.com/docs/search/query/operators-collectors/embedded-document.md#std-label-embedded-document-ref operator with the path specified as the embeddedDocuments field.

  • Use storedSource index option and specify the embeddedDocuments field in the returnScope query option.

You can also [configure dynamic mappings](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-configure-dynamic-mappings to automatically index fields that are part of the embedded document array element.

Considerations

Facet on Embedded Documents

You can facet on date, numeric, and string fields within embeddedDocuments type field to retrieve facet counts based on the number of matching embeddedDocuments elements. To do this, you must:

  1. Configure storedSource to store embeddedDocuments type fields.

  2. Set the query option returnScope.path as the embeddedDocuments field. To learn more about the syntax and usage of returnScope, see [Query, Filter, and Retrieve Arrays of Objects.](https://www.mongodb.com/docs/search/query/return-scope.md#std-label-fts-return-scope

To facet on fields within objects in arrays based on the number of matching root documents, index the path as a document type.

Stored Source for Embedded Documents

You can use the [storedSource](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition option to store and return fields inside an embeddedDocuments type. You can configure all or a subset of the fields to store or exclude from storage at each level of nesting. This allows you to return only the objects within the array that match the query criteria, rather than the entire root document. To learn more about the syntax for storedSource, see [Define Stored Source Fields in Your MongoDB Search Index.](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition

To return the stored field:

  • Specify returnScope.path option as the embeddedDocuments type field. To learn more, see [Query, Filter, and Retrieve Arrays of Objects.](https://www.mongodb.com/docs/search/query/return-scope.md#std-label-fts-return-scope

  • Set returnStoredSource to true to retrieve only the stored fields instead of entire documents from the collection. To learn more, see [Return Stored Source Fields.](https://www.mongodb.com/docs/search/query/return-stored-source.md#std-label-fts-return-stored-source-option

You can't include embeddedDocuments fields that were specified as storedSource.exclude at a higher-level.

embeddedDocuments Type Limitations

The following limitations apply when indexing with the embeddedDocument type:

  • You can use embeddedDocuments only on fields with up to 5 levels of nesting. An embeddedDocuments field can't have more than 4 parent embeddedDocuments fields.

  • You can't define a field inside the embeddedDocuments type as the deprecated [knnVector](https://www.mongodb.com/docs/search/indexes/field-types/knn-vector.md#std-label-fts-data-types-knn-vector type.

  • For [highlighting](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref fields within embedded documents, you must also index the parent of the field that you want to highlight as the [document](https://www.mongodb.com/docs/search/indexes/field-types/document-type.md#std-label-bson-data-types-document type.

  • The following operations require you to also index the parents of the embedded document child field as the [document](https://www.mongodb.com/docs/search/indexes/field-types/document-type.md#std-label-bson-data-types-document type:

  • [Facet](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref on fields within objects in arrays based on the number of matching root documents.

  • [Highlight](https://www.mongodb.com/docs/search/query/highlighting.md#std-label-highlight-ref fields within embedded documents. For an example, see the [How to Run MongoDB Search Queries Against Fields in Embedded Documents](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial tutorial.

  • [Sort](https://www.mongodb.com/docs/search/query/sort.md#std-label-sort-ref the parent documents by a nested field. You must also index the fields that you want to use for sorting.

2,100,000,000 Index Objects Limit

MongoDB Search stops replicating changes for indexes larger than 2,100,000,000 index objects per partition, on a replica set or single shard, where each indexed embedded parent document counts as a single object. Surpassing this limit may result in stale query results.

Using the embeddedDocuments field type can result in indexing objects over this index size limit, because each indexed embedded document is counted as a single object. If you create a MongoDB Search index that has or will soon have more than 2.1 billion index objects, use the [numPartitions](https://www.mongodb.com/docs/search/indexes/index-partition.md#std-label-fts-index-partition index option to partition your index (supported only on Search Nodes deployments) or [shard your cluster.](https://www.mongodb.com/docs/atlas/cluster-additional-settings.md#std-label-create-cluster-sharding

The exact number of index objects can vary based on the rate of document changes and deletions. The [Search Max Number of Lucene Docs](https://www.mongodb.com/docs/atlas/review-atlas-search-metrics.md#std-label-review-atlas-search-metrics metric shows the largest number of Lucene documents in a single partition of any search index within a replica set or shard.

For example, suppose the metric displays “1,500,000,000.” The index with the highest number of Lucene documents in a single partition has about 1,500,000,000 documents in that partition. If the index uses many partitions, it can contain more documents overall.

You can approximate the expected number of index objects in a single index by doing the following steps:

  1. Calculate the number of index objects per document. For every level of nesting, each embedded document counts as a separate index object.

shell number of index objects in document = 1 + number of nested embedded documents

  1. Multiply the number of index objects per document by the total number of documents in the collection

shell total number of index objects = number of index objects in document x total number of documents in collection

Note that this approximation is a lower bound.

Example:

Consider the collection named schools, described in this [tutorial](https://www.mongodb.com/docs/search/tutorial/embedded-documents-tutorial.md#std-label-embedded-documents-tutorial-sample-collection, and suppose the collection contains 1000 documents similar to the following:

{
  "_id": 0,
  "name": "Springfield High",
  "mascot": "Pumas",
  "teachers": [
    {
      "first": "Jane",
      "last": "Smith",
      "classes": [
        {
          "subject": "art of science",
          "grade": "12th"
        },
        ... // 2 more embedded documents
      ]
    },
    ... // 1 more embedded document
  ],
  "clubs": {
    "stem": [
      {
        "club_name": "chess",
        "description": "provides students opportunity to play the board game of chess informally and competitively in tournaments."
      },
      ... // 1 more embedded document
    ],
    ... // 1 more embedded document
  }
}

Now consider the index definition for the following fields in the schools collection:

Nested Array

The array of documents named teachers is indexed as the embeddedDocuments type with dynamic mappings enabled. However, the classes field isn't indexed. Use the following to calculate the index objects:

  1. Calculate the number of index objects per document.

shell Number of ``teachers`` embedded documents = up to 2 Total number of index objects per document = 1 + 2 = 3

  1. Multiply by the total number of documents in the collection.

shell Number of documents in the collection = 1000 Number of index objects per document = 3 Total number of index objects for collection = 1000 x 3 = 3000

If your collection has large arrays that might generate 2,100,000,000 index objects, you must [shard](https://www.mongodb.com/docs/atlas/cluster-additional-settings.md#std-label-create-cluster-sharding any clusters that contain indexes with the embeddedDocuments type.

Define the Index for the embeddedDocuments Type

  1. Create a search-index.json configuration file and specify the embeddedDocuments type.

json { "name": "default", "collectionName": "<collection>", "database": "<database>", "definition": { "mappings": { "dynamic": true|false | { "typeSet": "<typeSet-name>" }, "fields": { "<field-name>": { "type": "embeddedDocuments", "dynamic": true|false | { "typeSet": "<typeSet-name>" }, "fields": { "<field-name>": { <field-mapping-definition> } }, "storedSource": true | false | { "include" | "exclude": [ "<field-name>", ... ] } } } }, "typeSets": [ { "name": "<typeSet-name>", "types": [ { "type": "<field-type>", ... }, ... ] }, ... ] } }

  1. Connect to the Atlas CLI

In your terminal, connect to your cluster from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

  1. Create a MongoDB Search index.

Run the atlas clusters search indexes create command in your terminal, replacing <clusterName> with the name of the cluster, and <path-to-file> with the path to the search-index.json file:

shell atlas clusters search indexes create --clusterName <cluster-name> --file <path-to-file>

Configure embeddedDocuments Field Properties

The MongoDB Search embeddedDocuments type takes the following parameters:

Field Type Necessity Description Default
type String Required Human-readable label that identifies the field type. Value must be embeddedDocuments.
dynamic Boolean or Object Optional Flag that specifies whether to dynamically index using default type set or object that references the name of the configured typeSet that contains the list of field types to dynamically index. Value must be one of the following: boolean - set to true to recursively index all indexable field types or set to false to not dynamically index any of the dynamically indexable field types. For the list of field types that MongoDB Search dynamically indexes using the default type set, see [Enable Default typeSet.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-enable-dynamic-mappings; object - specify the name typeSets that contains the list of field types to index. To learn more, see dynamic.typeSet. If you set this to false, you must specify individual fields to index using fields object. You can also configure individual fields to index separately using the fields object. false
dynamic.typeSet String Optional Name of the typeSet array of objects that configures the field types to index. To learn more, see [Configure a typeSet.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-configure-dynamic-mappings
fields Object Optional Fields to index. This is required if dynamic is false. If dynamic is true, MongoDB Search indexes all indexable field types. You can also independently index individual fields using fields. MongoDB Search doesn't support indexing facet fields as part of an embeddedDocuments field. {}
storedSource Boolean or [Stored Source Definition](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition Optional Specifies fields in the documents to store for query-time look-ups using the [returnedStoredSource](https://www.mongodb.com/docs/search/query/return-stored-source.md#std-label-fts-return-stored-source-option option. You can store fields of all [MongoDB Search Field Types](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-bson-data-chart on MongoDB Search. Value can be one of the following: true, to store all fields; false, to not store any fields; [Object](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-document that specifies the fields to include or exclude from storage If omitted, defaults to false. To learn more, see [Define Stored Source Fields in Your MongoDB Search Index.](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition false
typeSets Array of Objects Optional Field types to index automatically using dynamic mappings. To learn about the field types that you can configure for dynamic mappings, see [Configure a typeSet.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-configure-dynamic-mappings
typeSets.[n].name String Required Human-readable label that identifies the configuration for the fields types to dynamically index.
typeSets.[n].types Array of Objects Required Field types, one per object, to index automatically using dynamic mappings.
typeSets.[n].types.[n].type String Required Field type to automatically index. You can also configure the settings for each field type. If you don't configure any settings, MongoDB Search uses the default values for the field type. To learn more about the field types that you can configure for dynamic mapping, see [Configure a typeSet.](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-configure-dynamic-mappings

Try an Example for the embeddedDocuments Type

The following index definition examples use collections in the [sample data](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets. After you [load the sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data, you can use these examples to index fields as the embeddedDocuments type.

To learn how to set up and run the following example code, see [Define the Index for the token Type](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-define-index-token-admin-api.

Basic Example

Automatically index all dynamically indexable fields inside the array of objects.

The following index definition for the sample_training.companies namespace indexes the array of objects in the products field. It also configures MongoDB Search to automatically index all dynamically indexable fields inside the objects in the products array.

{
  "name": "default",
  "collectionName": "companies",
  "database": "sample_training",
  "type": "search",
  "definition": {
    "mappings": {
      "fields": {
        "products": {
          "type": "embeddedDocuments",
          "dynamic": true
        }
      }
    }
  }
}

Dynamic Index Examples

Combine dynamic mappings with static mappings to index nested fields as different field types.

Enable Dynamic Indexing

The following index definition for the sample_training.companies namespace configures MongoDB Search to automatically index all dynamically indexable fields inside the objects in the products array. It also configures the category_code field to be indexed as the [token](https://www.mongodb.com/docs/search/indexes/field-types/token-type.md#std-label-bson-data-types-token type, which is not included in the default type set for dynamic mappings, to support MongoDB Search [facet (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/facet.md#std-label-fts-facet-ref queries against that field.


{
  "name": "default",
  "collectionName": "companies",
  "database": "sample_training",
  "type": "search",
  "definition": {
    "mappings": {
      "dynamic": true,
      "fields": {
        "products": {
          "dynamic": true,
          "type": "embeddedDocuments"
        },
        "category_code": {
          "type": "token"
        }
      }
    }
  }
}

Configure Dynamic Indexing

The following index example disables dynamic mappings at the root level and uses static mappings to index the relationships field as the embeddedDocuments type. It also applies the configured stringBooleanIndex typeSet to index only the string and boolean types the relationships array of objects. It applies the stringBooleanIndex typeSet to the nested person document to index only the boolean and string types in the person document.

{
  "name": "default",
  "collectionName": "companies",
  "database": "sample_training",
  "type": "search",
  "definition": {
    "mappings": {
      "dynamic": false,
      "fields": {
        "relationships": {
          "type": "embeddedDocuments",
          "dynamic": {
            "typeSet": "stringBooleanIndex"
          },
          "fields": {
            "person": {
              "type": "document",
              "dynamic": {
                "typeSet": "stringBooleanIndex"
              }
            }
          }
        }
      }
    },
    "typeSets": [
      {
        "name": "stringBooleanIndex",
        "types": [
          {
            "type": "boolean"
          },
          {
            "type": "string"
          }
        ]
      }
    ]
  }
}

Specified Fields Example

Index only specific fields in the array of objects.

The following index definition for the sample_training.companies namespace configures MongoDB Search to index onl

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