Leveraging Atlas Search for Powerful Text Search in MongoDB

Discover the capabilities of Atlas Search, a robust full-text search engine built into MongoDB Atlas. Learn how to create and manage search indexes, optimize search performance, and enhance your application's search functionality. This guide will equip you with the knowledge to unlock the full potential of Atlas Search for your MongoDB-based projects.



Indexing & Search

MongoDB Atlas provides a full-text search engine powered by Apache Lucene for searching documents in a collection.

Creating an Index

Follow these steps to create an index using the Atlas dashboard:

  1. Go to your Cluster name on the Atlas dashboard and click the Search tab.
  2. Click the Create Search Index button.
  3. Use the Visual Editor and click Next.
  4. Enter a name for your index. If you name it "default," you won't need to specify the index name in the $search pipeline stage.
  5. Select the Database (e.g., sample_mflix) and Collection (e.g., movies) to index, then click Next.
  6. Click Create Search Index and wait for the index to build.

Running a Query

Use the $search operator in your aggregation pipeline to utilize the search index.

Example

db.movies.aggregate([
  {
    $search: {
      index: "default", // Optional if index is named "default"
      text: {
        query: "star wars",
        path: "title"
      },
    },
  },
  {
    $project: {
      title: 1,
      year: 1,
    }
  }
])
        
Output

The first stage returns documents containing "star" or "wars" in the title field.
The second stage projects only the title and year fields from each document.