From indexing to querying: How MongoDB's full-text search stacks up against ElasticSearch.
Tags: database, mongodb, elasticsearch, search
Published: 2023-04-09 17:17:07

[MongoDB](https://www.mongodb.com/docs/) has been one of the most popular **NoSQL databases** in recent years, and its popularity continues to grow among developers and technology communities.
Some Major reasons for that is it's - **Flexibility, Scalability, Performance, Cloud-Based, Integration and community**.

But When it comes to **Full-text search** there are very few options available and suitable, in which **ElasticSearch** is the elephant amongst all, followed by **Solr**. 

So, What is **Full text search** ?

> Full-text search is a feature that allows you to use natural language queries to search through text data for specific words or phrases. It's commonly used in applications like search engines, e-commerce sites, and content management systems, where the ability to search through large amounts of text data quickly and accurately is critical.

MongoDB developer has been continuously working over the past year to provide us this full text search.

**How to use MongoDB Atlas Full text search:**
 
By Using MongoDB Atlas search we can easily search the terms into the specific fields of our database, also, we can use the  **Operators to search words or Phrases, Operators like - AND, OR, NOT**

For Using MongoDB Atlas Full text search, we need to take care some steps and rules/syntax.

1. **Create a MongoDB Atlas Cluster:** If you haven't already, sign up for MongoDB Atlas and create a new cluster. Make sure to choose a cluster tier that supports Full-Text Search, such as M10 or above.
2. **Enable Full-Text Search:** Once your cluster is configured, go to the Atlas UI's "Indexes" tab and click "Add Index." Select "Full-Text Search" as the index type and the fields to index. Then, to enable Full-Text Search for your cluster, click "Create Index. 
![MongoDB Atlas full text search](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzr44lw6iwqscj0pzyhs.png) 
3. **Configure Search:** After you've enabled Full-Text Search, you can configure your search settings using the "Search Configuration" tab in the Atlas UI. Here, you need to configure the [index](https://www.mongodb.com/docs/manual/core/index-text/).
4. I would recommend **Visual editor** for first time and it is easy to use.
5. In the configure Search after selecting Visual editor we need to name our Index and select the Database and collection where we need to do Text Search.
6. [Index configuration](https://www.mongodb.com/docs/manual/core/index-text/) and Field Mapping this is the most important step for our Full text search. In Index configuration we define **Analyzers** and **Fields/path** where we need to search, for example there is a field name products where you want to search product name. so, you will enter the field name in the **Field Mappings**
7. After making all these configuration you can click on save and it will start enabling all of your defined field and collection into full text search, this process will take a bit time and solely depend upon the size of the collection.
8. Now you will see a dashboard like this where you can test your search but in a limited way example- by clicking on **option query** you can search you single text or phrase in the interface.


![MongoDB Atlas search index](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vv5alb1wjh74tdiv8cg0.png)

For **searching more than one or multiple words with Operators** like - AND, OR, NOT you need to write queries **(see image for the reference)** 

![MongoDB Atlas search](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6l4s4gd8n8dc5vnbzty4.png)

Now Let's comes to **MongoDB Atlas Search Syntax and Basic Queries :**

```
    db.collection.aggregate([
      {
        $search: {
          index: "your-index-name",
          "text": {
            "query": "your-word",
            "path": "field"
          }
        }
      } 
    ])  
```

**Explanation -** 
In the above query we are using aggregation as search is always works with aggregation, and by using. 
**$search:** The $search stage performs a full-text search on the specified field or fields which must be covered by an Atlas Search index. defining Index is option, because if you not define index name it will always use the default one. but if you have multiple index then you need to defined. Also, best practice is to define index name.
**Query:** you will define the word which you are searching for. If you are searching for phrase then you need to change text: with phrase
**Path:** in the path we need to define the field where we are searching the word, We can define multiple paths in array forms too and it will only use those path which we defined at time of index making.

Example: 

```
{
  "_id" : 1,
  "type" : "apple",
  "description" : "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp.",
  "category" : "nonorganic",
  "in_stock" : false
},
{
  "_id" : 2,
  "type" : "banana",
  "description" : "Bananas are usually sold in bunches of five or six.",
  "category" : "nonorganic",
  "in_stock" : true
}
```
in the above data if we need to search a term like - Banana or Apple out of 2 documents above. we can easily search and return the document which contain this word.

So suppose we need to **Search** Bananas here and in the **field** description and my index name is search-fruits - 
**Query:**

```
    db.collection.aggregate([
      {
        $search: {
          index: "search-fruits", //define your index name
          "text": {
            "query": "Bananas",
            "path": "description"
          }
        }
      } 
    ])  
```
this above query return 1 document out 2 because only 1 document contains Bananas.

```
{
  "_id" : 2,
  "type" : "banana",
  "description" : "Bananas are usually sold in bunches of five or six.",
  "category" : "nonorganic",
  "in_stock" : true
}
```


There are **more advance queries like** - compound search which use **operators** like AND, OR, NOT (Should, Must, Mustnot) and features like - **autocompletes, fuzzy searches** etc. We will cover these advance topics in next article very soon!


**Few Points to consider before using MongoDB Atlas Full text search over ElasticSearch and Solr** - 

1. **Integrated within the database:** MongoDB Atlas Full-Text Search is integrated within the MongoDB database, whereas Elasticsearch and Solr are standalone search engines that must be integrated with a separate database. This integration can simplify the deployment and management process for users who already use MongoDB.
2. **Native JSON support:** MongoDB stores data in a JSON-like format, and Atlas Full-Text Search leverages this format for indexing and searching. Elasticsearch and Solr also support JSON, but they use a different data structure and query syntax.
3. **Automatic indexing:** MongoDB Atlas Full-Text Search automatically indexes data as it's added to the database, making it easier for developers to implement search functionality without the need for a separate indexing process.
4. **Scale-out architecture:** MongoDB Atlas is designed to be scalable and can handle large amounts of data and concurrent users. It allows for the creation of replica sets and sharded clusters, making it easier to scale out search capacity as needed.
5. **No need for dedicated search servers:** With MongoDB Atlas Full-Text Search, there is no need for a dedicated search server or infrastructure, unlike Elasticsearch or Solr. This can simplify the deployment and management process for users.
6. **Cost:** If you're already using MongoDB, using MongoDB Full-Text Search can be more cost-effective than using ElasticSearch, which requires additional infrastructure and management.

**Conclusion:** In the end, the use of MongoDB Atlas Full-Text Search is entirely dependent on your specific use case. While it lacks the advanced features of Elasticsearch or Solr, it does provide a number of advantages such as ease of use, integration with the MongoDB ecosystem, and scalability. Finally, it is up to you to evaluate your specific needs and determine which full-text search engine will best meet them.