Open In App

MongoDB Atlas Search

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In today’s digital world, the ability to quickly and efficiently search through vast amounts of data is important. Whether you’re building an e-commerce platform, a travel app, or any other application that depends on data retrieval, having a powerful search functionality can make all the difference.

In this article, we’ll explore the features of MongoDB Atlas Search, discuss its use cases, and go through some examples with different text searches to demonstrate how we can use it to enhance the search experience in our applications.

What is Atlas Search?

MongoDB Atlas Search is a fulltext search solution that allows users to query data on an Atlas cluster on MongoDB Atlas. It provides a seamless and scalable experience for building relevance-based app features. MongoDB Atlas is a multi-cloud database that helps deploy, manage, and scale MongoDB in the cloud.

It uses different cloud platforms such as Amazon Web Services(AWS), Microsoft Azure, and Google Cloud platform.

MongoDB Atlas Search provides rich indexing and advanced search functionality for applications or websites by eliminating to need to run a separate search system with your database.

The search process scales automatically as your data grows, ensuring smooth performance. Searching happens directly on the same nodes as our data, minimizing data transfer and delays.

Features of MongoDB Atlas Search

  • Faceted Navigation: MongoDB Atlas Search introduces powerful faceted navigation, allowing users to effortlessly filter and navigate through large datasets. For example, in an e-commerce application, users can refine search results by categories, brands, or other relevant facets, enhancing the overall user experience.
  • Autocomplete: With the Autocomplete feature, MongoDB Atlas Search predicts and suggests search queries in real-time as users type. This functionality significantly improves search efficiency and user engagement. For example, a search bar in an application can dynamically display relevant suggestions, helping users find what they need faster.
  • Fuzzy Search: MongoDB Atlas Search incorporates Fuzzy Search, enabling the system to find relevant results even when there are minor typos or variations in the search query. This is particularly useful for user-friendly search experiences, ensuring that users get meaningful results despite potential input errors.
  • Built-in Analyzers: With the built-in analyzers, MongoDB Atlas Search provides robust linguistic processing and text analysis. For example, in a multilingual application, the analyzer can intelligently handle different languages, ensuring accurate and context-aware search results for diverse user bases.
  • Highlighting: The Highlighting feature in MongoDB Atlas Search emphasizes search term occurrences in the result set, making it easy for users to identify relevant content. In a document-centric application, this feature ensures that users quickly spot the key information within the retrieved documents.

MongoDB Atlas Search Architecture

The Atlas Search mongot process, powered by Apache Lucene, works hand-in-hand with MongoDB to deliver a powerful and efficient search experience within the MongoDB Atlas cluster.

The mongot creates specialized maps (indexes) that help to find the relevant information within user data and constantly monitors changes in data through “change streams,” ensuring the search maps always reflect the latest information.

When we submit a search query, mongot acts as our guide, sifting through the maps and retrieving the documents that match your request, and sending it back to the user.

Atlas-Search-Architecture

Atlas Search Architecture

Atlas Search Indexes

It is the mapping between terms and documents that contain those terms, to enable faster retrieval of documents using certain identifiers. We can map the fields to index using the following:

  1. Dynamic Mapping: it automatically defines and indexes all the supported field types in the documents but it is stored on disk which may negatively impact the cluster performance.
  2. Static Mapping: It allows the user to explicitly define which fields to index and it optimizes the performance by providing advanced search requirements.

Create Atlas Search Index

We can create an Atlas Search index using the Atlas UI, Atlas Search API, Atlas CLI, or a supported MongoDB Driver in your preferred language.

Create an Atlas Search index Using Atlas UI

1. Sign in to your MongoDB Atlas account.

2. Navigate to the Atlas Search page for your project, select the desired project and cluster, and click on the Atlas Search tab.

3. Click Create Search Index.

4. Select an Atlas Search Configuration Method

1. Select either Atlas Search Visual Editor for a guided experience

Review the “default” index definition for the desired collection.

2. Select Atlas Search JSON Editor for advanced control and to edit rawindex definitions.

{
"mappings": {
"dynamic": true
}
}

6. Click Next.

7. Click Save Changes.

8. Click Create Search Index.

9. Close the You’re All Set! Modal Window. After a few minutes, the status column will show Active.

Create an Atlas Search index Using MongoDB Driver

1. Create a file named `create-index.js`

2. Copy and paste the following code into the create-index.js file.

const { MongoClient } = require("mongodb");

// connect to your Atlas deployment
const uri =
"<connection-string>";

const client = new MongoClient(uri);

async function run() {
try {

// set namespace
const database = client.db("sample_mflix");
const collection = database.collection("movies");

// define your Atlas Search index
const index = {
name: "default",
definition: {
/* search index definition fields */
"mappings": {
"dynamic": true
}
}
}

// run the helper method
const result = await collection.createSearchIndex(index);
console.log(result);
} finally {
await client.close();
}
}

run().catch(console.dir);

3. Replace the `<connectionstring>` in the query and then save the file. (Connection String)

4. Create the index by running the command.

node create-index.js

5. get the output

default

Output:

file

Created Search Index

Examples of Performing Atlas Search

1. Basic Text Search

Example 1: In this example, we are searching for doucments of students how have “computer science” as their skills in the students collections using text-query search by setting the `query` for the text we are searching for, as per here it is set to “computer science” and `path` to the specified field in which the seacrh will be performed , as per here “skills“.

db.students.aggregate([
{
$search: {
text: {
query: "computer science",
path: "skills",
},
},
},
])

Output:

Basic-Text-Search

Basic Text Search

2. Text Search with Sorting and Limit

Example 2: In this example, we are searching for doucments a text search within the “students” collection on the “skills” field for the query “programming.” The `$sort` stage is then applied to arrange the results based on the relevance score generated by the text search, with the highest scores appearing first. Finally, the `$limit` stage is used to restrict the output to the top 5 documents.

db.students.aggregate([
{
$search: {
text: {
query: "programming",
path: "skills",
},
},
},
{ $sort: { score: { $meta: "textScore" } } },
{ $limit: 5 },
])

Output:

Text-Search-with-Sorting-and-Limit

Text Search with sorting limit

3. Text Search with Language

Example 3: In this example, we are searching for documents within the “students” collection for the term “Data Science” in the “course” field. The `$search` stage initiates the search, specifying the query term, the target field for the search (“Data Science”), and the language for language-specific analysis (“english”).

db.students.createIndex(
{ "course": "text" }, { default_language: "english" }
);

db.students.find({
$text: {
$search: "Data Scienec",
$language: "english"
}
});

Output:

Text-Search-with-Language

Output

4. Geo Search

Example 4: In this example we are performing a geospatial search is performed within the “students” collection to get a set of documents where the “address.location” field is within a 5000-meter radius of the specified coordinates.

The $search` stage utilizes a compound query, specifically a “should” clause, indicating that the documents should match at least one of the specified conditions,`geo`clause checks for proximity to a specified location, `path`: “address.location” indicates the field containing geospatial coordinates, `near`specifies the desired location as a point with longitude and latitude coordinates and `maxDistance` : 5000 sets the maximum distance from the specified point in meters.

db.students.aggregate([
{
$search: {
compound: {
should: [
{
near: {
path: "address.location",
geometry: {
type: "Point",
coordinates: [12.9714,77.5946],
},
maxDistance: 5000, // in meters
},
},
],
},
},
},
])

Output:

Geo-Search

Output

5. Text Search with Faceted Navigation

Example 5: In this example, we are performing a facted navigation to get a structured summary of the distribution of “data science” across different facets such as courses, skills, and graduation years within the “students” collection. By performing a text search for the query “data science” across the “course” and “skills” fields of the documents in the first stage, then in the second stage utilizes the `$facet` operator to organize the results into distinct facets, namely “courses,” “skills,” and “graduation_years.” Each facet is then processed using `$sortByCount` to determine the frequency of occurrences for unique values within the associated categories.

db.students.aggregate([
{
$search: {
text: {
query: "data science",
path: ["course", "skills"],
},
},
},
{
$facet: {
courses: [{ $sortByCount: "$course" }],
skills: [{ $sortByCount: "$skills" }],
graduation_years: [{ $sortByCount: "$graduation_year" }],
},
},
])

Output:

Text-Search-with-Faceted-Navigation

Output

Use Cases of MongoDB Atlas Search

  1. E-commerce Search: Enhance product search functionality in e-commerce applications. Developers can implement a feature-rich search experience, allowing users to find products based on attributes, descriptions, and specifications quickly.
  2. Content Management Systems (CMS): Improve search capabilities within CMS platforms. Developers can use Atlas Search to enable efficient and accurate searches for articles, documents, and multimedia content.
  3. User Profile Search: Implement advanced user profile search in social networking or directory applications. Developers can use Atlas Search to enable users to find others based on various profile attributes or keywords.
  4. Geospatial Search: Implement location-based search functionality in applications that require geospatial queries. Developers can use Atlas Search to find nearby points of interest, businesses, or locations.
  5. Searchable Knowledge Bases and FAQs: Enhance search capabilities in knowledge bases or FAQ sections of applications. Developers can use Atlas Search to provide users with quick and relevant answers to their queries.

Conclusion

Overall, MongoDB Atlas Search offers a powerful and versatile solution for enhancing search functionality within applications and websites. Its robust features, including faceted navigation, autocomplete, fuzzy search, and more, contribute to an improved user experience and efficient information retrieval.

The ability to seamlessly integrate full-text search capabilities directly into MongoDB Atlas eliminates the need for a separate search system, ensuring scalability and optimal performance as data grows. The article touches upon the creation of search indexes, explaining dynamic and static mapping options, and provides insights into the architecture of MongoDB Atlas Search.

The use of Atlas Search indexes is essential for optimizing performance, allowing users to define and index specific fields based on their application’s requirements.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads