Reputation: 777
NodeJS
search_key = new RegExp('.*' + req.params.search_key + '.*', 'i');
Item.find({product_name:search_key}).exec(function (err, items) {
console.log(items) );
});
Here I can search product name with the search_key. But my problem is, my product name is "COMPLAN MILK BISCUITS 100GM
". If I search with "BISCUITS COMPLAN
", its not finding that product. I need to find "BISCUITS COMPLAN
" and "COMPLAN BISCUITS
" based on contain in search.
Upvotes: 0
Views: 678
Reputation: 16805
you need to create text index to achieve your goal and then search from text indexed field. mongo shell command to create text index for product_name
field
db.colectionName.createIndex( { product_name: "text" } );
then you can search using $text
and $search
. doc
db.collectionName.find({ $text: { $search: "BISCUITS COMPLAN" } });
no need to use new RegExp(
just can use like:
Item.find({ $text: { $search: req.params.search_key } }).exec(function (err, items) {
console.log(items) );
});;
Upvotes: 2
Reputation: 111306
You need to use the $text
operator for that.
So instead of:
Item.find({product_name: search_key})...
Something like:
Item.find({product_name: {$text: {$search: search_key}}})...
Note: You need to have a text index for that.
Upvotes: 0