Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial string matching in Mongodb [duplicate]

Tags:

regex

mongodb

Lets say I have a bunch of mongodb records like so, which are all strings:

{myRecord:'foobarbazfoobaz'}
{myRecord:'bazbarfoobarbaz'}
{myRecord:'foobarfoofoobaz'}
{myRecord:'bazbarbazbazbar'}

I need to be able to partial string match in two ways:

1) I want to match on 'foobar' so it returns:

'foobarbazfoobaz'
'foobarfoofoobaz'

Note that here, 'foobar' is a partial string that is matched against any of the records from the beginning of the string. It doesn't matter if 'foobar' turns up later in the string. As long the first six characters of 'foobar' match against the the first six characters of the record, I want to get it back.

2) I need to be able match on 'baz%%%baz' so it returns:

bazbarbazbazbar

Here 'baz%%%baz' matches the first three characters of any of the records, ignores the next three, then matches against the final three. Again, it doesn't matter if this pattern occurs later in the string, I am just interested in if I can match it from the beginning of the string.

I think there is some kind mongo regex to do this (hopefully) but I am terrible when it comes to regex. Any help would be greatly appreciated.

This is for a web application where users are searching for sequences of events on a timeline and they will always have to search from the beginning, but can leave blanks in the search if they wish to.

like image 756
Jamie Avatar asked Sep 27 '22 14:09

Jamie


1 Answers

You can try $regex operator

1) I want to match on 'foobar'

db.collection.find({"myRecord":{"$regex":"^foobar*"}})

I need to be able match on 'baz%%%baz'

db.collection.find({"myRecord":{"$regex":"^baz.{3}baz"}})

Hope it will help

like image 165
Rohit Jain Avatar answered Sep 30 '22 08:09

Rohit Jain