Adding Autocomplete To Your NextJS Applications With Atlas Search
Rate this tutorial
Imagine landing on a webpage with thousands of items and you have to scroll through all of them to get what you are looking for. You will agree that it's a bad user experience. For such a website, the user might have to leave for an alternative website, which I'm sure is not what any website owner would want.
Providing users with an excellent search experience, such that they can easily search for what they want to see, is crucial for giving them a top-notch user experience.
The easiest way to incorporate rich, fast, and relevant searches into your applications is through MongoDB Atlas Search, a component of MongoDB Atlas.
In this guide, I will be showing you how I created a text search for a home rental website and utilize Atlas Search to integrate full-text search functionality, also incorporating autocomplete into the search box.
This search will give users the ability to search for homes by country.
Let's look at the technology we will be using in this project.
If you'd like to follow along, here's what I'll be using.
I chose this framework because it provides a simple setup and helps with optimizations such as automatic code splitting and optimized performance for faster load times. Additionally, it has a strong community and ecosystem, with a large number of plugins and examples available, making it an excellent choice for building both small- and large-scale web applications.
NodeJS and ExpressJS: We will be using these to build our back end. Both are used together for building server-side web applications.
MongoDB Atlas is a fully managed cloud database service provided by MongoDB. It's a cloud-hosted version of the popular NoSQL database (MongoDB) and offers automatic scalability, high availability, and built-in security features. With MongoDB Atlas, developers can focus on building their applications rather than managing the underlying infrastructure, as the service takes care of database setup, operation, and maintenance.
MongoDB Atlas Search is a full-text search and analytics engine integrated with MongoDB Atlas. It enables developers to add search functionality to their applications by providing fast and relevant search results, including text search and faceted search, and it also supports autocomplete and geospatial search.
MongoDB Atlas Search is designed to be highly scalable and easy to use.
Let's get to work!
Once the clone is completed, in this repository, you will see two sub-folders:
mdbsearch: Contains the Nextjs project (front end)
backend: Contains the Node.js project (back end)
Open the project with your preferred text editor. With this done, let's set up our MongoDB environment.
We will be working with the
sample-airbnbsample data from MongoDB for this application because it contains appropriate entries for the project.
The API for our front end will be provided by the Node.js back end. To establish a connection to your database, let's create a
.envfile and update it with the connection string.
Update .env as below
Run the below code
This command will start the server. You should see a message in your console confirming that the server is running and the database is connected.
With the back end running, let's start the front end of your application. Open a new terminal window and navigate to the
mdbsearchfolder. Then, install all the necessary dependencies for this project and initiate the project by running the npm command. Let's also create a
.envfile and update it with the backend url.
Create a .env file, and update as below:
Start the application by running the below command.
With this data loading from the MongoDB database, next, let's proceed to implement the search functionality.
To be able to search through data in our collection, we need to follow the below steps:
The MongoDB free tier account gives us the room to create, at most, three search indexes.
From the previously created cluster, click on the Browse collections button, navigate to Search, and at the right side of the search page, click on the Create index button. On this screen, click Next to use the visual editor, add an index name (in our case,
search_home), select the
listingsAndReviewscollection from the
sample_airbnbdatabase, and click Next.
From this screen, click on Refine Your Index. Here is where we will specify the field in our collection that will be used to generate search results. In our case ---
addressfield is an object that has a
countryproperty, which is our target.
Therefore, on this screen, we need to toggle off the Enable Dynamic Mapping option. Under Field Mapping, click the Add Field Mapping button. In the Field Name input, type
address.country, and in the Data Type, make sure String is selected. Then, scroll to the bottom of the dialog and click the Add button. Create another Field Mapping for
property_type. Data Type should also be String.
The index configuration should be as shown below.
At this point, scroll to the bottom of the screen and click on Save Changes. Then, click the Create Search Index button. Then wait while MongoDB creates your search index. It usually takes a few seconds to be active. Once active, we can start querying our collection with this index.
MongoDB provides a search tester, which can be used to test our search indexes before integrating them into our application. To test our search index, let's click the QUERY button in the search index. This will take us to the Search Tester screen.
Remember, we configure our search index to return results from
property_type. So, you can test with values like
apartment, etc. These values will return results, and we can explore each result document to see where the result is found from these fields.
Test with values like
brasil. These will return no data result because it's not an exact match. MongoDB understands that scenarios like these are likely to happen. So, Atlas Search has a fuzzy matching feature. With fuzzy matching, the search tool will be searching for not only exact matching keywords but also for matches that might have slight variations, which we will be using in this project. You can find the details on fuzzy search in the .
With the search index created and tested, we can now implement it in our application. But before that, we need to understand what a MongoDB aggregation pipeline is.
Now that we have the search index configured, let's try to integrate it into the API used for this project. Open
backend/index.jsfile, find the comment Search endpoint goes here , and update it with the below code.
Start by creating the route needed by our front end.
In this endpoint,
/search/:searchwe create a two-stage aggregation pipeline:
$searchuses the index
search_home, which we created earlier. The
$searchstage structure will be based on the query parameter that will be sent from the front end while the
$projectstage simply returns needed fields from the
This endpoint will receive the
property_type, so we can start building the aggregation pipeline. There will always be a category property. We can start by adding this.
We don't necessarily want to send all the fields back to the frontend, so we can use a projection stage to limit the data we send over.
Finally, we can use the
aggregatemethod to run this aggregation pipeline, and return the first 50 results to the front end.
The result of the pipeline will be returned when a request is made to
At this point, we have an endpoint that can be used to search for homes by their country.
From our project folder, open the
searchNowfunction and update it with the below code.
handleChangefunction, let update it with the below code
With the above update, let's explore our application. Start the application by running
npm run devin the terminal. Once the page is loaded, choose a property type, and then click on "search country." At the top search bar, type
brazil. Finally, click the search button. You should see the result as shown below.
The search result shows data where
address.countryis brazil and
property_typeis apartment. Explore the search with values such as braz, brzl, bral, etc., and we will still get results because of the fuzzy matching feature.
Now, we can say the experience on the website is good. However, we can still make it better by adding an autocomplete feature to the search functionality.
Most modern search engines commonly include an autocomplete dropdown that provides suggestions as you type. Users prefer to quickly find the correct match instead of browsing through an endless list of possibilities. This section will demonstrate how to utilize Atlas Search autocomplete capabilities to implement this feature in our search box.
In our case, we are expecting to see suggestions of countries as we type into the country search input. To implement this, we need to create another search index.
From the previously created cluster, click on the Browse collections button and navigate to Search. At the right side of the search page, click on the Create index button. On this screen, click Next to use the visual editor, add an index name (in our case,
country_autocomplete), select the listingsAndReviews collection from the sample_airbnb database, and click Next.
From this screen, click on Refine Your Index. We need to toggle off the Enable Dynamic Mapping option.
Under Field Mapping, click the Add Field Mapping button. In the Field Name input, type
address.country, and in the Data Type, this time, make sure Autocomplete is selected. Then scroll to the bottom of the dialog and click the Add button.
At this point, scroll to the bottom of the screen and Save Changes. Then, click the Create Search Index button. Wait while MongoDB creates your search index --- it usually takes a few seconds to be active.
Once done, we should have two search indexes, as shown below.
With this done, let's update our backend API as below:
backend/index.jsfile, and update it with the below code:
The above endpoint will return a suggestion of countries as the user types in the search box. In a three-stage aggregation pipeline, the first stage in the pipeline uses the
$searchoperator to perform an autocomplete search on the
address.countryfield of the documents in the
country_autocompleteindex. The query parameter is set to the user input provided in the URL parameter, and the
highlightparameter is used to return the matching text with highlighting.
The second stage in the pipeline limits the number of results returned to one.
The third stage in the pipeline uses the
$projectoperator to include only the
address.countryfield and the search highlights in the output
Let's also update the front end as below. From our project folder, open the
mdbsearch/components/Header/index.jsfile. Find the
handeChangefunction, and let's update it with the below code.
The above function will make a HTTP request to the
country/autocompleteand save the response in a variable.
With our code updated accordingly, let's explore our application. Everything should be fine now. We should be able to search homes by their country, and we should get suggestions as we type into the search box.
Voila! We now have fully functional text search for a home rental website. This will improve the user experience on the website.
To have a great user experience on a website, you'll agree with me that it's crucial to make it easy for your users to search for what they are looking for. In this guide, I showed you how I created a text search for a home rental website with MongoDB Atlas Search. This search will give users the ability to search for homes by their country.
MongoDB Atlas Search is a full-text search engine that enables developers to build rich search functionality into their applications, allowing users to search through large volumes of data quickly and easily. Atlas Search also supports a wide range of search options, including fuzzy matching, partial word matching, and wildcard searches. Check out more on MongoDB Atlas Search from the official .
How to Use Custom Archival Rules and Partitioning on MongoDB Atlas Online Archive
May 31, 2023