7

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.

Jamie
  • 165
  • 1
  • 3
  • 11
  • No doubt I will just get shouted down but I can't see how in is duplicate - but in any case the (apparent) original version didn't really help me solve the particular problem I had run into. – Jamie Oct 13 '15 at 03:13

2 Answers2

10

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

Rohit Jain
  • 2,052
  • 17
  • 19
  • This soves the first problem - thanks! – Jamie Oct 02 '15 at 05:00
  • For the second problem, almost works but would you know how I can specifiy a certain amount of characters to be ignored between 'baz' and 'bar'. The second query, as well as picking up 'bazbarbazbazbar' would also pick up stuff like 'bazbarbarbarbaz'. thanks so much for looking at this! – Jamie Oct 02 '15 at 05:02
  • Please try db.collection.find({"myRecord":{"$regex":"^baz.{3}baz"}}) – Rohit Jain Oct 02 '15 at 09:31
1

Hang on - just found a way to deal with the second case, which turns out to be unexpectedly straightforward: {"myRecord":{"$regex":"^baz.{3}.baz"}} I probably should spend some time learning how to use regex!

Jamie
  • 165
  • 1
  • 3
  • 11