MongoDB text search partial words

In this MongoDB tutorial, we are going to discuss “MongoDB text search partial words”. We will also cover this with different operations and examples. These are the following topics that we are going to cover in this tutorial:

  • MongoDB text search partial words
  • MongoDB text search partial word query
  • MongoDB text search partial word index
  • MongoDB text search partial word example
  • MongoDB text search partial word all
  • MongoDB text search partial word multiple
  • MongoDB compass text search partial words
  • MongoDB text search partial word not working
  • MongoDB text search partial word python

MongoDB text search partial words

In MongoDB, we can search the text by using the $text query operator and it is used to perform text searches on a collection with a text index. It provides text indexes to support text search queries on string content.

You must have a text index on your collection to perform text search queries. The $text will tokenize the search string using whitespace and most perform a logical OR of all such tokens in the search string.

The below example will help you to understand, how you can find the partial word in the collection.

db.users.find( { "$text" : { "$search" : "DEANÉL" } } ) => FOUND (search with diacriticSensitive is false)

db.users.find( { "$text" : { "$search" : "DEANE" } } ) => FOUND (Partial search)

MongoDB text search partial word query

MongoDB is an excellent use case for Elasticsserch. And, it’s really good and helps in ad-hoc analysis and search results on that kind of data. If you need performance then a MongoDB schema turned for minimal indexes is excellent.

The following query will use to search text partial words in MongoDB.

The $text expression has the following syntax:

{
  $text:
    {
      $search: <string>,
      $language: <string>,
      $caseSensitive: <boolean>,
      $diacriticSensitive: <boolean>
    }
}

The text query document with the following fields:

FieldTypeDescription
$searchstringA string that MongoDB uses to
query the text index.
$languagestringOptional, it defines the list of stop words for the search and the rules for the stemmer and tokenizer. If it is not specified then the search uses the default language of the index.
$caseSensitivebooleanOptional, A boolean flag to disable case-sensitive search.
$diacriticSensitivebooleanOptional, A boolean flag to enable diacritic sensitive search against version 3 text indexes.

Now, we more understand with the help of an example.

Example:

The following documents were going to insert into the store collection:

db.store.insertMany([
{ _id: 1, subject: "coffee", author: "xyz", views: 50 },
{ _id: 2, subject: "Coffee Shopping", author: "efg", views: 5 },
{ _id: 3, subject: "Baking a cake", author: "abc", views: 90  },
{ _id: 4, subject: "baking", author: "xyz", views: 100 },
{ _id: 5, subject: "Café Con Leche", author: "abc", views: 200 }
])

After inserting the documents into the collection. Now, we will create the index and use the $search operation to search the text string in the collection.

Here, we can create one-time scripts or create all the indexes to have full control over that process.

Here, we are creating an index for the subject field:

db.store.createIndex({ subject: "text" })
MongoDB text search partial words
Create index in MongoDB

Now, we use the following query to search specific string coffee:

db.store.find( { $text: { $search: "coffee" } } )

This query returns the documents that include the word coffee in the indexed subject field;

MongoDB text search partial words example
MongoDB text search partial words example

We successfully return the document that contains the term coffee or more precisely the stemmed version of the word.

Read: MongoDB Auto Increment ID

MongoDB text search partial word index

An index is a list of all the names that are designed to help readers to find where they are discussed in the text. The index is used to store all the values of a specific field or set of fields.

The text indexes can include any field where the value is a string and an array of string elements and it only supports text search queries on string content. We must have to create a text index on the collection to perform text search queries.

The following syntax is used to create an index for the collection:

db.<collection>.createIndex( { field_name: "text" } )

We can create multiple fields for the text index. The following syntax shows create index multiple fields:

db.<collection>.createIndex(
   {
     field_name_1: "text",
     field_name_2: "text"
   }
 )

We will more understand with the help of an example:

Example:

The following documents were inserted into the review collection:

db.review.insertMany([
{ "_id" : 1, "Name" : "David", "Age" : 22, "Gender" : "Male" },
{ "_id" : 2, "Name" : "Peter", "Age" : 24, "Gender" : "Male" },
{ "_id" : 3, "Name" : "Sammy", "Age" : 23, "Gender" : "Female"}
])

Now, we will create text indexes for all the fields:

db.review.createIndex(
   {
      Name: "text",
      Gender: "text"
   }
)

Here, we created the text index for the Name and Gender field.

MongoDB text search partial word index
Create text index for all the fields

We successfully created the text index for all the columns.

Now, the following query will use to search partial words from the documents of the collection.

db.review.find(
     { 
        Name: "Peter", 
        $text: { $search: "Male" }
     }
)

Here, we search text index where the Name is Peter with search index Male.

MongoDB text search partial word index example
MongoDB text search partial word index

We successfully return the documents where the text string is “Male” and the Name is “Peter”.

Read: What are indexes in MongoDB Database and we can use them?

MongoDB text search partial word example

As we discuss the text search partial word like how we can easily find the partial words of the documents. Here, we will more understand with the help of an example.

Example:

The following documents were inserted into the board collection:

db.board.insertMany([
{ _id: 1, book: "MongoDB in Action", author: " Kyle Banker", views: 150 },
{ _id: 2, book: "Scaling MongoDB", author: "Kristina Chodorow", views: 106 },
{ _id: 3, book: "MongoDB and PHP", author: "Steve Francia", views: 190  },
{ _id: 4, book: "Mongodb for Web Development", author: "Mitch Pirtle", views: 160 },
{ _id: 5, book: "The Little MongoDB Book", author: "Karl Seguin", views: 200 }
])

Now, we have to create indexes for all the strings in the collection to have full control over that process.

db.board.createIndex({ "book": "text", "author": "text" })
MongoDB text search partial word example
Create an index for all the column

After creating the text index for all the columns, we can use the $search operator and find the document:

db.board.find( 
      { author: "Karl Seguin", 
        $text: { $search: "MongoDB" }}
)

This command will display all the documents where the author name is “Karl Seguin” and the index field the book contains the terms “MongoDB”.

MongoDB text search partial word
MongoDB text search a partial word

We successfully retrieved all the documents according to the given condition.

Read: MongoDB remove a field from the document

MongoDB text search partial word all

Sometimes we have to find or search all the partial text words as per the question demand. So, we will learn to search all the partial words of the document with the help of an example.

Example:

The following documents were inserted into the library collection.

db.library.insertMany([
{ _id: 1, book: "MongoDB in Action", author: " Kyle Banker", views: 150 },
{ _id: 2, book: "Scaling MongoDB", author: "Kristina Chodorow", views: 106 },
{ _id: 3, book: "MongoDB and PHP", author: "Steve Francia", views: 190  },
{ _id: 4, book: "Mongodb for Web Development", author: "Mitch Pirtle", views: 160 }
])

After that, we will create the text index for the document field. And, for creating the text index use the following query:

db.library.createIndex( {   book: "text" })

Here, we create a text index of the book field in the library collection.

Note that, you must have a text index on your collection to perform text search queries.

Now, the following query is used to search all the partial words of the document.

db.library.find( { $text: { $search: "MongoDB" }  } )

Here, the $search operator will find all the documents where the string is MongoDB. And, the find() will return all the text search partial words.

MongoDB text search partial word all example
MongoDB text search partial word all example

We successfully return all the documents where the search text partial word is “MongoDB”.

Read: Missing before statement MongoDB

MongoDB text search partial word multiple

In our real-time scenarios, we have to text search on multiple fields of the documents. And, we must have the text index to perform all the text search queries. We understand this with the help of an example so let’s get started.

Example:

The following documents were inserted into the relation collection.

db.relation.insertMany([
{"subject":"Joe", "content":"best friend", "likes": 60, "year":2015, "language":"english"},
{"subject":"Dogs", "content":"Cats", "likes": 30, "year":2015, "language":"english"},
{"subject":"Cats", "content":"Rats", "likes": 55, "year":2014, "language":"english"},
{"subject":"Rats", "content":"Joe", "likes": 75, "year":2014, "language":"english"}
])

As we must have the text index to perform the text search query so the following query is used to create the text index for all the fields of the documents:

db.relation.createIndex(
    {
       subject: "text",
       content: "text",
       language: "text"
    }
)

Here, we are creating the text index of all the fields subject, content, and language.

MongoDB text search partial word multiple
Create an Index for all the fields

We successfully created the text index for all the fields. Now, we use the $search operator to find multiple field text partial words.

db.relation.find({$text: {$search: "cats"}}).sort({content: -1})

Here, we search the string cats and display all the fields and also applied the sort() method to display multiple fields in descending order as per the content field.

MongoDB text search partial word multiple example
MongoDB text search partial word multiple fields

We successfully return all the multiple fields in descending order where the string is cats.

Read: MongoDB two-phase commit

MongoDB compass text search partial words

In MongoDB compass, we can also search the partial text words from the documents of the collection. In this topic, we learn to find text search partial words with the help of an example in MongoDB compass:

Example:

You have to follow all the following steps to search text partial words in MongoDB compass:

  • Open the MongoDB compass
  • Use the database and collection where you want search the partial words.
  • You can also create a new database and collection also insert the documents into the collection.
  • Here we are using the Company database and person collection and inserted some documents into the person collection.
MongoDB compass text search partial words
MongoDB compass create the database and collection
  • Now, we know the text index is must required to perform text search queries.
  • Click on Indexes and after that click on CREATE INDEX button for creating the index on the collection.
MongoDB compass text search
Create an index for the document fields
  • We will create text indexes for all the document fields.
MongoDB compass create index for text search
MongoDB compass create indexes

Here, we created indexes for all the fields and also add more fields by clicking on ADD ANOTHER FIELDS button. We can also change the name of the index and if we don’t define any name then it will use the default name for the index. After that, click on the CREATE INDEX button for creating the index.

  • Now, we will apply the $search operation and search the particular search string text.
  • Click on the FIND button that will return all the documents as per the condition.
{ $text: {$search : "Male" } }     # define this in FILTER block

{ Name: 1 }      # define this in SORT block

Here, the FILTER command is used to search text string is Male and the SORT command is used to sort the documents in ascending order as per the Name field.

MongoDB compass text search partial words example
MongoDB compass text search partial words

We have successfully retrieved all the documents of the person collection in ascending order as per the Name field where Gender is Male.

Read: MongoDB create and change user password

MongoDB text search partial word not working

A few days back, when I was working on a task to search partial words from the collection and I was not able to search certain words.

I am doing the task in the right way like insert documents, create required indexes but when I applied the $search operation to find the text string then it doesn’t return anything.

Example:

The following documents were inserted into the data collection.

db.data.insertMany([
{ "content": "How are you?", "likes": 60, "year": 2015},
{ "content": "After death life?", "likes": 60, "year": 2015},
{ "content": "took other apple", "likes": 60, "year": 2015}
])

After that, we will create the text indexes for all the fields of the data collection.

db.data.createIndex( 
      { content: "text" },
      { default_language: "english"}
)

Here, we create the text index on the content and use the default language is English.

db.data.find( { $text: { $search: "other"}} )

Here, after executing the above query it doesn’t return anything for reference check the below snapshot:

MongoDB text search partial word not working
MongoDB text search partial word not working

Thus, after executing the command it doesn’t return anything.

So to resolve this problem, I read a lot of blogs on the web and try to figure out the problem. And, I found one solution to this problem.

Actually, the text index is not giving me the result because of the stop words. Certain words don’t preserve while creating the text indexes. For example (in English): a, an, the, are, etc.

You can go through the link to check the list of stop words. If the word is present in this list then that is the only reason the text index is unable to return the documents.

Note, You can also check this link to check the list of stop words as per your language.

Now, the solution to this problem is we have the change the default_language to none while creating indexes. The error occurred because we used English that remove all the stop words and doesn’t return any document.

So use the following command to create the index for the data collection.

db.data.createIndex( 
      { content: "text" },
      { default_language: "none"}
)

Here, we create the indexes and specify the default_language is none. The none means no specific language and tells that create the text indexes for all the words present there.

MongoDB text search partial word not working solution
MongoDB create the text index

Now, we search the text “other” by using the $search operator using the following query.

db.data.find( { $text: { $search: "other"}} )
MongoDB text search not working solution
MongoDB text search partial words

We successfully resolve the problem and return all the documents where the text string is the “other”.

Read: MongoDB find multiple conditions

MongoDB text search partial word python

In this topic, we will search the partial words from documents using python. We will more understand with the help of an example.

Example:

The below documents were inserted into the example collection.

db.example.insertMany([
{"_id": "101", "name": "James", "age": "26", "city": "Los Angeles"},
{"_id": "102", "name": "Michael", "age": "27", "city": "Los Angeles"},
{"_id": "103", "name": "Robert", "age": "28", "city": "Los Angeles"},
{"_id": "104", "name": "Boby", "age": "19", "city": "New York"},
{"_id": "105", "name": "James", "age": "25", "city": "London"}
])

As we know text index is must be required while searching the text partial words.

Now, we use the following python query to create the index and find the text partial words.

from pymongo import TEXT, MongoClient
# Create a pymongo client 
client = MongoClient('localhost', 27017) 
    
# database instance 
db = client['myDB'] 
    
# collection instance 
doc = db['example'] 
  
# Creating text index all the field of document
res = doc.create_index([ ("name", TEXT) ])

#MongoDB text search partial words
for i in doc.find( {"$text": { "$search": "James"} } ):
    print(i)

Here, The pymongo library is used to work with MongoDB and also import two classes TEXT and MongoClient. The MongoClient class is used to make the connection to the MongoDB server. And, we must have to create the text index and that we will create by using the TEXT class. we created the text index for all the fields and use the $search operation to find where the text string “James”.

MongoDB text search partial word python
MongoDB text search partial word python

Output:

MongoDB text search partial word python example
MongoDB text search partial word python

In the output, you can see we successfully return all the documents fields where the text string is “James”.

Read: Create indexes in MongoDB using python?

Also, take a look at some more MongoDB tutorials.

In this tutorial, we have learned about “MongoDB text search partial words” with different operations and examples. And we have also covered the following list of topics:

  • MongoDB text search partial words
  • MongoDB text search partial word query
  • MongoDB text search partial word index
  • MongoDB text search partial word example
  • MongoDB text search partial word all
  • MongoDB text search partial word multiple
  • MongoDB compass text search partial words
  • MongoDB text search partial word not working
  • MongoDB text search partial word python

Leave a Comment