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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失