duanchao4445 2014-03-12 07:12
浏览 57
已采纳

MongoDB:将PHP代码转换为Python代码

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 ); 
  • 写回答

1条回答 默认 最新

  • doucha4054 2014-03-12 08:15
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?