To search text in MongoDB, mongodb supports query operations that search text in document.

For search text, we are going to use $text operator and text index.

Sample Database


[{"name": "swift","type": "hatchback","price":"800000"},
 {"name": "ciaz","type": "sedan","price":"1000000"},
 {"name": "baleno","type": "hatchback","price":"850000"},
 {"name": "baleno rs","type": "hatchback","price":"950000"},
 {"name": "scross","type": "crossover","price":"11500000"},
 {"name": "brezza","type": "suv","price":"990000"},
 {"name": "gypsy","type": "suv","price":"750000"}
]    

Text Index

Text Index are used to search text strings from collection having strings or array of strings.

Its not possible to search string without Text Index.

Without Text String

Error: error: {
        "ok" : 0,
        "errmsg" : "text index required for $text query",
        "code" : 27,
        "codeName" : "IndexNotFound"
}
db.suzuki.find({$text:{$search:"hatchback"}})

Text String

To Search text from name and type, use code below. This will exclude price in text search as price is not included.

db.suzuki.createIndex( { name: "text", type:"text"} )

Text Operator

Now we will use $text operator to perform text search on collection with text index, i.e. name and type.

{
        "_id" : ObjectId("5eb81a2fbe672314a54326a0"),
        "name" : "baleno",
        "type" : "hatchback",
        "price" : 850000
}
{
        "_id" : ObjectId("5ebbf05dbcbb54669293d48d"),
        "name" : "baleno rs",
        "type" : "hatchback",
        "price" : 950000
}
db.suzuki.find({$text:{$search:"baleno rs"}}).pretty()

This will search baleno rs text in collection. As we can, there are two variants of baleno in collection, this will search both.

Search Exact Phrase

To search exact phrase by wrapping string in double quotes.

{
        "_id" : ObjectId("5ebbf05dbcbb54669293d48d"),
        "name" : "baleno rs",
        "type" : "hatchback",
        "price" : 950000
}
db.suzuki.find({$text:{$search:"\"baleno rs\""}}).pretty()

This will search baleno rs exact phrase, which is one.

{
        "_id" : ObjectId("5ebbf05dbcbb54669293d48d"),
        "name" : "baleno rs",
        "type" : "hatchback",
        "price" : 950000
}
db.suzuki.find({$text:{$search:"\"baleno rs\""}}).pretty()

This will search baleno rs exact phrase, which is one.