0

I want keyword search in nodejs with mongodb as DB, I tried few things but din't work.

const response = await db.collection.find({ $text: { $search:  searchstring }});

this is working for text search but not for keyword search.

for ex: if I am searching John , it is giving me all doc containing John but if I am searching with jo , it is giving empty result.

Can anyone please suggest how to search with keyword.

James Z
  • 12,209
  • 10
  • 24
  • 44
tiya
  • 117
  • 1
  • 3
  • 14

1 Answers1

0

Try using regular expressions:

const keyword = 'jo';
const r1 = new RegExp(`\\b${keyword}`, 'i'); // 'i' stands for ignore letter case

const response = await db.collection.find({ text: { $regex: r1 } });

This code will retrieve all documents, where text starts with 'jo', ignoring the case.

  • I tried this but it is giving empty result – tiya Mar 30 '23 at 11:22
  • if (searchstring !== undefined) { const r1 = new RegExp(`\\b${searchstring}`, 'i'); const response = await db.collection.find({ text: { $regex: r1 } }); console.log(response); return response?response : null; } – tiya Mar 30 '23 at 11:23
  • @tiya in your code you should use template literals, because you're searching for `searchString`: `new RegExp(\`\\b${searchstring}\`, 'i');` it should work as expected – thundergrove Mar 30 '23 at 12:14