MongoDB

# MongoDb Text Search in fields of document

Search functionality is required in many applications having their own databases.Search functionality basically refers to a function that takes in key words as its parameters and returns documents that contain those keywords in one or more fields (As per your requirement). Manually checking the keywords in fields of all the documents is a very tiring process,but MongoDb comes to our rescue and provide the search functionality to us in a few easy steps.

Text Search is enabled by default in versions later than 2.6,but for earlier versions run the following command:

db.adminCommand({setParameter:true,textSearchEnabled:true})

Let us take a sample collection named 'articles' of 3 documents

{
"id":1
   "title" : "Article on Binary Trees "
}
{"id":2
  "title" : "Article on Arrays "
}
{
"id":3
   "title" : "Article on Binary Trees and Linked Lists "
}

Now, we will create an index on the field "title" which means we will enable text search on the field "title" by the command:

db.articles.ensureIndex({title:"text"})

To enable searching on multiple fields you can provide more fields in previous command like:

db.articles.ensureIndex({field1:"text",field2:"text", ...})

Having done that we are through to all the procedure and we can move to search command. The search command with key words ="Trees Lists" is as follows:

db.articles.find({$text:{$search:"Trees Lists "}})

which will return

{
"id":1 
  "title" : "Article on Binary Trees "
}
{
"id":3
   "title" : "Article on Binary Trees and Linked Lists "
}

But if you see,the second document in our result is more relevant to our search as it contains both the keywords "Trees" and "Lists" so naturally we would want to display it on top of other document.For this purpose MongoDb generates a textScore for each returned result. If we sort the results by decreasing order of textScore we will get results in desired manner.The command would be :

db.articles.find({ $text: { $search:"Trees Lists" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } })

This would provide the results in the desired order as

{
"id":3
  "title" : "Article on Binary Trees and Linked Lists "
}
{
"id":1
  "title" : "Article on Binary Trees "
}


By Gaurav Israni

@gaurav.israni


Learn More


  • MongoDb Text Search in fields of document