A Practical Example Using MongoDB Atlas Search

Learn how to use MongoDB Atlas Search.

Chukwuemeka Maduekwe
5 min readFeb 10, 2022

Let’s say you’re about to build a project that has lots of stuff in it, for example, a blog, the collections in your database might be ‘users’ and ‘posts’, and that alone is enough for your database. Now, as your site grows, you might want to:

  1. Implement a function that fetches similar posts to what the user has just read based on keywords, in a bid to keep the user on your site.
  2. You would also love a situation where your users can easily search for a topic and get a result that is highly related to what they want.
  3. You want an auto-complete as users type their search phrase.

All this and more can be done, but in a situation where you have a narrow timeframe, will you be able to implement all this perfectly and also be able to add taste to it like Highlighting user's search phrase, autocomplete in the search box, fuzzy search(A situation whereby you match wrong spellings, synonyms and more), not to discourage you a bit will it be a full-text search and not just a search where you match keywords, ID’s, or the whole string, bear in mind that when a user is searching, it’s quite different from when you are comparing password for authentication (where you don’t give room for error), users are likely to make mistakes or use the wrong phrase in their search, will your functions be scalable and performant, all this should dawn on you, before you engage in an endless task that might not bear the fruit you envision.

Allow me to introduce you to Atlas Search: Atlas Search is an embedded full-text search in MongoDB Atlas that gives you a seamless, scalable experience for building relevance-based app features.

MongoDb Atlas Search
MongoDB Atlas Search

MongoDB Atlas Search or Atlas Search for short as we would use in this post is an embedded full-text search that gives you a seamless, scalable experience for building relevance-based app features. You might be wondering like I was, when I was first introduced to Atlas Search by Marcus, who is a Senior Product Manager of Atlas Search at MongoDB, I felt nostalgic, that this would be a whole new database different from the popular document-oriented, NoSQL MongoDB I know, and this, kind of, discouraged me from even trying it out, probably as a result of not knowing what it offers at the outset. But I can tell you there’s a whole lot more to Atlas Search and this is a feature that companies will be willing to spend a fortune to have and it comes to us at no cost.

Let’s dive in, To keep this simple we’ll be working on a basic app, we can call it Transearch, this app serves as an account manager where users can add transactions such as debit or credit, title, description, and amount, it also saves a current balance from all transactions. The key here is to show how fast and easy it can be to locate any transaction with the little detail you have concerning the transaction.

A live version of this app can be found here and the full source code can be gotten from Github, here and here, the former being the client and the latter being the server code. More details can be found in the README.md section of their respective Github repo.

I used Next.js to build the frontend and other tools included are Material-UI, Redux, and SASS, While on the backend, I used Node.js, Express, MongoDB, Mongoose, and bcryptjs. The main point of this app is to show how easy it is to integrate Atlas Search into your app, be it a new or an existing app. Read the docs for a quick intro and after you have cloned the project and created a database on MongoDB, I’ll explain the search functions:

Client Search Function

As you already guessed and that you did right, what this search handler does in the client app can divide into two, the first being the basic ‘.find({})’ while the second is where we call the powerful ‘$search’ API from our server. Mind you, we call atlasSearch API from our server only when we have a search phrase, as this will throw an error. When the transactions page load initially, we call fetchTransWithSearchPhrase(id), the id parameter we pass to fetchTransWithSearchPhrase is our auth ID. Other times when a search phrase is not defined we call fetchTransWithoutSearchPhrase (id).

We call the atlasSearchTransaction handler only when a valid Search phrase is passed to it. Explanation of code, based on line numbers in the below picture:

Server Search Function
  1. On line 3, we destructure the searchPhrase and company in the req.body, i.e. the data coming from our client fetchTransWithSearchPhrase handler.
  2. On line 5, we define our aggregation, $search is where the magic happens. In-text object, we describe what our search is all about. We pass searchPhrase to query, i.e. what our user is searching for, path refers to the fields in our document we want to search against; When it just one field, you can pass it as a single text, else it an array like so: [“title”, “keywords”, “description”], ‘fuzzy: {}’ refers to the fact that a user might make a spelling error, and the great thing that fuzzy does is make that searchPhrase right and also return similar words.
  3. On line 16, $project refers to the field we want to return from the aggregation.
  4. On line 30, we used $match, we did this because we are storing all transactions in one collection which might not be ideal, what we could do is create a unique collection for each user. In our transaction schema, we have a path for a company or rather a user, and what we are doing with the match is to make sure we are fetching from the right owner of the transaction. Mind you, $match or $sort can’t come before $search.
  5. On line 35, what ‘$sort: { _id: -1 }’ does is to reverse the order of the result, i.e. a kind of stack data structure, so the last item added becomes the first item in the returned array
  6. On line 40, the $limit is used to set the max number of documents that can be returned.
  7. On line 44, we pass the aggregate option to the collection and call the aggregate method which either returns an error or result.
  8. On line 48, we send the result back to the client.

That marks the end of this section, I hope you’ve seen how easy it is to use Atlas Search in a new or an existing project.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

--

--

Responses (1)