Reputation: 2387
I have a message system where I want different message handlers to be called depending on the patterns of the incoming messages.
I have this collection:
[
{ Pattern: "^a", Handler: "Handler1" },
{ Pattern: "^b", Handler: "Handler2" },
{ Pattern: "^c", Handler: "Handler3" }
]
For a given message (a string) I now want to find the first element where the message matches the pattern and then extract the Handler name.
That is, for the message "b bla bla bla", I want to extract "Handler2".
Note, I don't want to use a regex query to find some string in the database, it is the other way around: I want to find the element having a pattern which matches a given string.
My solution right now is to fetch the entire list of patterns and then iterate and match over all the patterns in my application code and it works fine, but I am wondering if there is some efficient mongo query which can be used instead?
Upvotes: 0
Views: 654
Reputation: 17649
You should be fine the way you're doing it right now if the number of patterns is small.
If you have a large number of patterns you'll become a victim of a variation of the Halting problem: There no easy way to know if a pattern matches (or not) until you actually execute it with your input string (think of the pattern as a mini-program).
Or: Given that there is only a finite set of inputs (which is probably not the case), you could store all possible inputs and their corresponding patterns in MongoDB.
Hope that helps.
Upvotes: 1
Reputation: 36624
Likely you need to implement the matching check yourself and apply it using map/reduce style.
Upvotes: 0