I want add search functionality. I need to search any document by starting letter.
Suppose, we have to some document like-
Apple Industry
Samsung Industry
Xioami Industry
Ahua Industry
Sumatech Industry
When user search a then it should give the result which one start with a like-
Ahua Industry
Apple Industry
You can see the result show alphabetically
I already create a regex like this-
{ Industry: { '$regex': 'a', '$options': 'i' } }
But it show all the content that contain a.
Like-
It show every content because all the content contain a.
How can I solve that. Can anyone help me.
You need to add the startWith modifier to your regex. I'm not sure how this object gets converted to the regex, but here you go:
{ Industry: { '$regex': '^a.*', '$options': 'i' } }
function matchText(query) {
const text = ['Apple Industry',
'Samsung Industry',
'Xioami Industry',
'Ahua Industry',
'Sumatech Industry'
];
const regex = new RegExp(`^${query}.*`, 'i');
text.forEach((item) => console.log(item.match(regex)));
}
matchText('a');
matchText('ap');