Modeling data for keyword searches
Searching for keywords in a document is a common operation for many applications. We can search using an exact match or by using a $regex
regular expression in the content of a field that contains text. MongoDB also provides the ability to search using an array of keywords.
The basic need for a keyword search is to be able to search the entire document for keywords. For example, there could be a need to search a document in the products
collection, as shown in the following code:
{ name : "Macbook Pro late 2016 15in" ,
manufacturer : "Apple" ,
price: 2000 ,
keywords : [ "Macbook Pro late 2016 15in", "2000", "Apple", "macbook", "laptop", "computer" ]
}
We can create a multikey index in the keywords
field, as shown in the following code:
> db.products.createIndex( { keywords: 1 } )
Now, we can search in the...