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 );
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 |
.