Seif Labidi
Seif Labidi

Reputation: 23

How to search in mongo with misspelled words

I'm building my VOD website and I'm allowing search via video titles and keywords and labels etc.
So my problem is if a user enters for exemple a persons name or a keyword miss written the search command that i use for mongo dB won't find it so the user will think that it's non existent while its just misspelled . I'm new to this domain so I'm struggling I'm using net core 3 and mongo dB

Upvotes: 1

Views: 1614

Answers (2)

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5669

what you need is fuzzy search which mongodb doesn't offer for free. they have it on their paid atlas services.

however, you can do-it-yourself by storing double metaphone key codes for your data along with the original values and use the built-in mongodb $text search feature to get back misspelled matches.

for ex: if user enters gogle and you'd want to match google from the database.

if you want a readymade solution for .net core, have a look here

Upvotes: 1

Karim Chaari
Karim Chaari

Reputation: 402

How about searching by regex ? i.e: you can search users by their Id, or names (you can also search by 2 different fields like firstName and lastName:

  const regexString = `${keyword}`;
  const regex = new RegExp(regexString);
  const matches = ['firstName', other fields here .. ].map(field => ({
    [field]: { $regex: regex, $options: 'i' },
  }));

  const data = await Users.find(
    {
      $and: [
        {
          userId,
        },
        { $or: matches },
      ],
    },
  );

Upvotes: 1

Related Questions