Partial match on string when using filter

When using the API on a collection, how would you search entries that contain a specific string?

Using Mongo syntax, I’d do something like {"title":/word/}, but it doesn’t like that. Also tried wrapping quotes around it or use .* and the likes. The SQL % also doesn’t seem to work. I suppose it’s just trying to search for the literal string and look for a 100% match.

Does anyone know?

Also, let’s say I want to search in two fields, for example title and description, would that be possible? And it would be even nicer if I could use equivalents of AND and OR, if I want a string to be present in both fields or either one.

Thanks in advance.

{title: {$regex: "word"}}

Sometimes things can be so simple :). Thanks @artur!

Edit:

If you want to use OR/AND in your queries, check our these links: $or, $and.

Using $or:

{ $or: [ { title: "word1"}, {title: "word2"} ] }

In the above example, you’re searching for an exact match of “word1” or “word2” in the field title.

If you want to search for entries where the field title contains “word1” or “word2”, you could do this:

{ title: {$regex: "(word1|word2)"} }

Or if you want to search for the same word in multiple fields, you could do it like so (in my example, the collection has fields title and text):

{ $or: [ { title: {$regex:"word"}}, {text: {$regex:"word"}} ] }
{ title: {$regex:"(word1|word2)"}}

use the power of regex :wink:

1 Like

Haha, I actually did that in my tests, but when I posted back here it slipped my mind. Of course that’s the better solution! :laughing:

I fixed my post.