0

I was searching a way to combine $in and $regex in mongoDB and found exactly the same question with exactly what I want to do. The problem is that the answer is in PHP and I don't have an idea about it. The question is here.

Do you know if I can find anywhere the same sollution in Python code?

$user_query = preg_replace("/[[:blank:]]+/"," ", $user_query);
$arr_query = explode(' ', $user_query);

if (count($arr_query) > 1) {
    $tmp = array();

    foreach ($arr_query as $q) {
        $tmp[] = new MongoRegex( "/". $q ."/" );
    }

    $who['keywords'] = array('$in' => $tmp);

} else {
    $who['keywords'] = new MongoRegex( "/". $user_query ."/" );
}

$db->collection->find( $who ); 
4
  • All the code is doing is passing a list of words inside a $regex operator inside $in. So is what you are actually looking for a way to match any of the words in the list?
    – Neil Lunn
    Commented Mar 12, 2014 at 8:00
  • I want exactly the same thing like the example of the original question. I have a list of words and I want to check it with a regex inside a list of keywords in my mongodb.
    – Tasos
    Commented Mar 12, 2014 at 8:02
  • I was asking if you wanted to apply some regex epression in particular, because all this code does is sets up the regex to match the word. My reason is there is a different way to write the regex if that is what you want.
    – Neil Lunn
    Commented Mar 12, 2014 at 8:07
  • No. I don't think so. I just want to search if the words from the list is any part of the keywords in mongodb. Without a certain pattern. Just part of the keyword. Examples economics -> macroeconomics, economic -> economics, signal -> digital signal
    – Tasos
    Commented Mar 12, 2014 at 8:13

1 Answer 1

1

This is what the code does. Given the string:

"one two three"

It gets converted to the equivalent of :

{ "$in": [
    {"$regex": "one"},
    {"$regex": "two"},
    {"$regex": "three"}
]}

But this regex is exactly the same:

{"$regex": "one|two|three"}

And to get that, then all you need to do is replace the whitespace with a |.

1
  • Thank you a lot. It was easier than I thought!
    – Tasos
    Commented Mar 12, 2014 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.