0
0
MongoDBquery~5 mins

Atlas search overview in MongoDB

Choose your learning style9 modes available
Introduction

Atlas Search helps you find information quickly inside your MongoDB data. It makes searching easier and faster.

You want to find text inside many documents fast, like searching words in articles.
You need to search for products by name or description in an online store.
You want to filter and sort search results by relevance or date.
You want to add autocomplete suggestions when users type in a search box.
You want to search across multiple fields like title, tags, and content at once.
Syntax
MongoDB
db.collection.aggregate([
  {
    $search: {
      index: "default",
      text: {
        query: "search term",
        path: "fieldName"
      }
    }
  }
])

The $search stage is used inside an aggregation pipeline.

You specify the search index and the text query with the field to search.

Examples
Searches the 'books' collection for documents where the 'title' contains 'history'.
MongoDB
db.books.aggregate([
  {
    $search: {
      text: {
        query: "history",
        path: "title"
      }
    }
  }
])
Searches 'products' collection in both 'name' and 'description' fields for 'laptop'.
MongoDB
db.products.aggregate([
  {
    $search: {
      text: {
        query: "laptop",
        path: ["name", "description"]
      }
    }
  }
])
Sample Program

This query searches the 'movies' collection for documents where the 'genre' field contains 'adventure'. It returns the first 3 matching movies.

MongoDB
db.movies.aggregate([
  {
    $search: {
      text: {
        query: "adventure",
        path: "genre"
      }
    }
  },
  {
    $limit: 3
  }
])
OutputSuccess
Important Notes

You must create a search index in Atlas before using $search.

$search works only inside aggregation pipelines.

Atlas Search supports many types of queries like text, autocomplete, phrase, and more.

Summary

Atlas Search lets you quickly find text inside MongoDB collections.

Use the $search stage in aggregation to run search queries.

It supports searching multiple fields and different query types.