MongoDB: Text search (exact match) using variable

Chakraborty picture Chakraborty · May 4, 2017 · Viewed 9.4k times · Source

MongoDB 3.4

I have a value in a variable. val1 = "Fort Minor"

I need to search in a collection stores (with text index on name field) with documents as

db.stores.insert([
     { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
     { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
     { _id: 3, name: "Coffee Shop", description: "Just coffee" },
     { _id: 4, name: "Fort Coffee", description: "Discount clothing" },
     { _id: 5, name: "Java Shopping", description: "Indonesian goods" }
])


when I text search the collection using the variable

db.City.find({$text:{$search: val1}})

it returns the _id : 4 document, since it contains Fort.

I need to do an exact match but using the variable.

The above search should return only when val1 = "Fort Coffee"

Answer

Mihir Bhende picture Mihir Bhende · May 4, 2017

When you do text search, it has many internal steps like tokenizing your work, analyzing the lowest stem of the word(e.g. to match cooking & coocked as both are derived from basic work "cook"). If you are expecting an exact match, you are not actually looking for a texual search but you are looking for a normal query.

Hence,

If you do this :

db.City.find({$text:{$search: "Fort Minor"}})

It will try to find all documents which have fort, minor, minority, forting etc in it.

If you do below :

db.City.find({ name : "Fort Minor"})

If will give you the document with exact match.

However, here is the catch :

IF you search all lowercase like :

db.City.find({ name : "fort minor"})

It will not give you what you are expecting.

To resolve this, go for regular expression :

db.user.find( { name: /^Fort Minor$/i } );