MongoDB Atlas Search

MongoDB Atlas Search is a full-text search solution that is integrated into MongoDB Atlas, to provide a seamless and scalable experience for building relevance-based search queries.

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 MongoDB Atlas Search tutorial, we will 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.

Table of Content

  • What is Atlas Search?
  • MongoDB Atlas Search Features
  • MongoDB Atlas Search Architecture
  • Atlas Search Indexes
  • Create Atlas Search Index
  • MongoDB Atlas Search Example
  • Use Cases of MongoDB Atlas Search
  • Difference Between MongoDB Search and Atlas Search

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 the 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 dataminimizing data transfer and delays.

MongoDB Atlas Search Features

  • 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 retrieving the documents that match your request, and sending it back to the user.

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

Follow the steps below to create an Atlas Search Index using Atlas UI

Step 1: Log into your MongoDB Atlas account.

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

Step 3: Click Create Search Index.

Step 4: Select an Atlas Search Configuration Method:

  • Step 4a: Select Atlas Search Visual Editor for a guided experience.
  • Step 4b: Select Atlas Search JSON Editor for advanced control and to edit raw index definitions.

Step 5: Review the “default” index definition for the desired collection.

bIn the Atlas Search JSON Editor, add the following index definition:

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

Step 7: Click Next.

Step 8: Click Save Changes.

Step 9: Click Create Search Index.

Step 10: 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

Step 1: Create a file named create-index.js.

Step 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);

Step 3: Replace the <connection-string> in the query and then save the file

Step 4: Create the index by running the command.

node create-index.js

Step 5: Get the output:

default

Output:

Created Search Index

MongoDB Atlas Search Example

After learning all the basics now let’s see how to perform search in MongoDB Atlas. We have covered different examples of MongoDB Atlas Search in different scenarios.

Basic Text Search in MongoDB Atlas Example

In this example, we are searching for documents of students who 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 search will be performed, as per here “skills“.

Query:

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

Output:

Basic Text Search

Text Search with Sorting and Limit in MongoDB Atlas Example

In this example, we are searching for documents 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.

Query:

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

Output:

Text Search with sorting limit

Text Search with Language in MongoDB Atlas Example

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”).

Query:

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

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

Output:

Output

Geo Search in MongoDB Atlas Example

In this example, we are performing a geospatial search 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.

Query:

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

Output:

Output

Text Search with Faceted Navigation in MongoDB Atlas Example

Example 5: In this example, we are performing a faceted 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.

Query:

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

Output:

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.

Difference Between MongoDB Search and Atlas Search

Let’s look at the differences between MongoDB Search and Atlas Search.

Feature MongoDB Search Atlas Search
Functionality Basic text search functionality using text indexes Advanced full-text search capabilities with Apache Lucene integration
Customization Limited customization options Extensive customization options for search queries, including fuzzy search, autocomplete, synonyms, and custom scoring
Integration Integrated within MongoDB Integrated into MongoDB Atlas for seamless use
Performance Basic search capabilities High-performance search engine with rich feature set
Use Cases Suitable for simple text searches Ideal for complex search requirements in applications with large datasets
Maintenance Requires manual setup and maintenance Fully managed solution within MongoDB Atlas

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, explains 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.

You can check the official MongoDB Atlas Search Documentation here

MongoDB Atlas Search- FAQs

What is Atlas Search in MongoDB

Atlas Search is a full-text search solution integrated into MongoDB Atlas, offering advanced search capabilities using Apache Lucene. It enables seamless building of relevance-based features in applications within the MongoDB ecosystem.

How to find data in MongoDB Atlas

To find data in MongoDB Atlas, you can query a collection using specific methods like finding by document ID or date. Utilize the MongoDB Query API within a function to read documents from your Atlas cluster, employing operators and patterns to handle common use cases effectively.

How to create an Atlas search index in MongoDB

To create an Atlas Search index in MongoDB, you need to follow these steps:

  1. Select a tab corresponding to the aggregation pipeline stage you want to use.
  2. Choose one or more operators or collectors to perform a specific search on your collection.
  3. Review your Atlas Search query syntax and then run it in your application using a driver, mongosh, Compass, or the Search Tester.

What are the benefits of Atlas Search?

It eliminates the need for a separate search system, offering a seamless, scalable, and fully managed solution for enhancing application search capabilities.

What is MongoDB Atlas search autocomplete?

Atlas Search autocomplete is a feature that allows you to perform searches for words or phrases that contain a sequence of characters from an incomplete input string.



Contact Us