$text Operator in MongoDB – Simple Guide

In this guide, I will explain to you how to use the $text operator in MongoDB.

The $text operator makes room for users to perform a text search or a string search in MongoDB. We may even find a specific set of string characters or a word from a string with the help of the $text operator.

This article aims to provide multiple examples of how to use the $text operator in MongoDB for different types of text searches. So, let us get this guide started!

The $text Operator Syntax in MongoDB

Let us take a quick look at the $text operator in MongoDB.

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

The operator comes with one required parameter 3 other optional parameters tied to it. we can perform a word search, non-exact phrase search, exact phrase search, and even case-sensitive characters search. We will look at examples for all of these conditions within this guide.

Let us proceed further into our guide to look at some examples.

Creating Text Index for Operand Collection

Before we start, we must create a text index for the operand collection.

Text indexes should be either strings or arrays of strings. When performing a text search query, keep in mind that your collection must have a text index, and a collection can only have one text index that covers multiple fields.

Had we directly started the operation, we would have seen such an error:

Error: error: {
        "ok" : 0,
        "errmsg" : "text index required for $text query",
        "code" : 27,
        "codeName" : "IndexNotFound"
}

To create an index, let us first look at the syntax:

db.collectionName.createIndex( { field: “text” } )

Setting a text index for the operand collection:

> db.tweets.createIndex({tweet:"text"})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

Perfect! We are now good to go.

Using the $text operator in MongoDB

Let us take a look at a few examples on using the $text operator in MongoDB.

Below is the collection we will be using throughout the guide.

> db.tweets.find().pretty()
{
        "_id" : ObjectId("6054b3a1a27b2e0d548db83b"),
        "tweet" : "Omg, I found this little surprise on my door!",
        "likes" : 5,
        "shares" : 3,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("6054b838e578451124643d84"),
        "tweet" : "What a good day!",
        "likes" : 5000,
        "shares" : 300,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796774"),
        "tweet" : "Good boy!",
        "likes" : 15,
        "shares" : 13,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796775"),
        "tweet" : "With my friends at the Yale Cafe :)",
        "likes" : 900,
        "shares" : 3,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796776"),
        "tweet" : "It is too cold here",
        "likes" : 1353,
        "shares" : 23,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796777"),
        "tweet" : "Booting my W101 Storm. Anyone wanna join me for Catacombs?",
        "likes" : 897,
        "shares" : 6,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796778"),
        "tweet" : "Finally got the ring I had been longing for from Catacombs! ",
        "likes" : 1849,
        "shares" : 51,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}

So, we have 7 documents inside here.

Searching Text Using the $text Operator in MongoDB

In this example, I will search for a text in our collection. I want to look for all those tweets that contain the case insensitive text “good”.

> db.tweets.find({$text:{$search:"good"}}).pretty()
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796774"),
        "tweet" : "Good boy!",
        "likes" : 15,
        "shares" : 13,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("6054b838e578451124643d84"),
        "tweet" : "What a good day!",
        "likes" : 5000,
        "shares" : 300,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}

Great! We found 2 such documents!

Searching Case Sensitive Text Using $text Operator in MongoDB

In this example, I will search for text that is case-sensitive. I want documents that contain the text “Good” with a capital G.

> db.tweets.find({$text:{$search:"Good", $caseSensitive: true}}).pretty()
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796774"),
        "tweet" : "Good boy!",
        "likes" : 15,
        "shares" : 13,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}

You must have noticed I set the option $caseSensitive as true and received just 1 document this time.

Performing a Non-Exact Match Phrase Search Using the $text Operator

In this example, we will do a non-exact phrase search on our collection. This means the operator will match all those documents that match ALL the words or phrases inside the query.

I thought I go a little creative and rather frame a random sentence. The text input I am passing is “got the cold ring from Catacombs”.

> db.tweets.find({$text:{$search:"got the cold ring from Catacombs"}}).pretty()
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796778"),
        "tweet" : "Finally got the ring I had been longing for from Catacombs! ",
        "likes" : 1849,
        "shares" : 51,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796777"),
        "tweet" : "Booting my W101 Storm. Anyone wanna join me for Catacombs?",
        "likes" : 897,
        "shares" : 6,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796776"),
        "tweet" : "It is too cold here",
        "likes" : 1353,
        "shares" : 23,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}

Amazing we found 3 documents that did a non-exact match to our specified phrase.

Performing an Exact Match Phrase Search Using the $text Operator

In this example, I will be performing an exact match phrase search. For this, I will wrap my input string between escaped double-quotes.

> db.tweets.find({$text:{$search:"\"found this little surprise\""}}).pretty()
{
        "_id" : ObjectId("6054b3a1a27b2e0d548db83b"),
        "tweet" : "Omg, I found this little surprise on my door!",
        "likes" : 5,
        "shares" : 3,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}

Perfect! We have found 1 document that matches our query.

Excluding a Search Term while Querying with the $text Operator

In this example, I will exclude a search term while I query using the $text operator in MongoDB.

Here are 3 examples where I think we can perform this operation.

Example 1:

> db.tweets.find( { $text: { $search: "good -boy" } } ).pretty()
{
        "_id" : ObjectId("6054b838e578451124643d84"),
        "tweet" : "What a good day!",
        "likes" : 5000,
        "shares" : 300,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}

Example 2:

> db.tweets.find( { $text: { $search: "good -day" } } ).pretty()
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796774"),
        "tweet" : "Good boy!",
        "likes" : 15,
        "shares" : 13,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}

Example 3:

> db.tweets.find( { $text: { $search: "Catacombs -storm" } } ).pretty()
{
        "_id" : ObjectId("618f8bc0ffd0e09a7a796778"),
        "tweet" : "Finally got the ring I had been longing for from Catacombs! ",
        "likes" : 1849,
        "shares" : 51,
        "user" : ObjectId("6054b3a1a27b2e0d548db83a"),
        "__v" : 0
}

Conclusion

Learn to use the $text operator in MongoDB from this guide.

References

https://www.geeksforgeeks.org/search-text-in-mongodb/

https://docs.mongodb.com/manual/reference/operator/query/text/#examples

Aneesha S
Aneesha S
Articles: 171