Skip to content
Rate this page
Thanks for your feedback
Thank you! The feedback has been submitted.

Get free database assistance or contact our experts for personalized support.

Create a search index

Create a search index

Before you can run full-text search queries, create a search index on the collection.

Use the db.collection.createSearchIndex() method to create a search index.

Follow these steps:

  1. Create a search index.

    db.<collection>.createSearchIndex(
      "<name>",
      "<type>",
      {
        <definition>
      }
    )
    

    createSearchIndex() accepts the following parameters:

    Field Type Required Description
    name string No Name of the index. Defaults to default if omitted.
    type string No Index type. Specify search or vectorSearch. The default is search.
    definition document Yes Defines the index configuration.
    Example: Create a search index
    db.docs.createSearchIndex({
      name: "search_idx",
      definition: {
        mappings: {
          dynamic: true
        }
      }
    })
    

    Output

    search_idx
    
  2. Verify that the index is ready.

    db.docs.getSearchIndexes()
    

    Index creation runs asynchronously. Wait until the index status is READY before running search queries.

    Output

    [
      {
        name: "search_idx",
        status: "READY",
        queryable: true,
        ...
      }
    ]
    
  3. Run a full-text search.

    Search the collection
    db.docs.aggregate([
      {
        $search: {
          index: "search_idx",
          text: {
            query: "future",
            path: "text"
          }
        }
      }
    ])
    

    Output

    [
      {
        text: "Vector search is the future"
      }
    ]
    

Next steps

Update a search index

Delete a search index

Learn more

$vectorSearch aggregation stage