【问题标题】:How to make "LIKE" query work in MongoDB?如何使“LIKE”查询在 MongoDB 中工作?
【发布时间】:2011-04-27 00:44:33
【问题描述】:

我有一个街道名称列表,我想选择所有以“Al”开头的名称。 在我的 MySQL 中,我会做类似的事情

SELECT * FROM streets WHERE "street_name" LIKE "Al%"

MongoDB 使用 PHP 怎么样?

【问题讨论】:

    标签: php sql mongodb sql-like


    【解决方案1】:

    使用正则表达式:

    db.streets.find( { street_name : /^Al/i } );
    

    或:

    db.streets.find( { street_name : { $regex : '^Al', $options: 'i' } } );
    

    http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

    把它变成 PHP:

    $regex = new MongoRegex("/^Al/i");
    $collection->find(array('street_name' => $regex));
    

    【讨论】:

    • 是的,但是在 php 中呢? $database->streets->find(array("street" => "/^Al/i"));
    • 作为一个附带问题,这在原始速度方面如何比较?使用正则表达式过滤数据集的想法让我有点畏缩......不过是 mongodb 的新手。
    • 只要正则表达式以 ^ 开头(即匹配字符串的开头),就会使用索引。
    【解决方案2】:

    见:http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart

    另外,强烈建议只使用 PHP 中的本机 mongodb 连接器,而不是包装器。它比任何包装器都快。

    http://php.net/class.mongodb

    【讨论】:

      【解决方案3】:

      这是我的工作示例:

      <?php
      use MongoDB\BSON\Regex;
      $collection = $yourMongoClient->yourDatabase->yourCollection;
      $regex = new Regex($text, 's');
      $where = ['your_field_for_search' => $regex];
      $cursor = $collection->find($where);
      //Lets iterate through collection
      

      【讨论】:

        【解决方案4】:

        $collection.find({"name": /.*Al.*/})

        或者,类似的,

        $collection.find({"name": /Al/})

        您正在寻找某处包含“Al”的内容(SQL 的 '%' 运算符等效于正则表达式''.*'),而不是在字符串开头锚定“Al”的内容。

        【讨论】:

          【解决方案5】:

          MongoRegex 已被弃用。
          使用MongoDB\BSON\Regex

          $regex = new MongoDB\BSON\Regex ( '^A1');
          $cursor = $collection->find(array('street_name' => $regex));
          //iterate through the cursor
          

          【讨论】:

            【解决方案6】:
            <?php
            $mongoObj = new MongoClient();
            $where = array("name" => new MongoRegex("^/AI/i"));
            $mongoObj->dbName->collectionName->find($where);
            ?>
            

            View for more details

            【讨论】:

              【解决方案7】:

              你也可以这样做

              ['key' => ['$regex' => '(?i)value']]
              

              【讨论】:

                猜你喜欢
                • 2011-03-19
                • 1970-01-01
                • 2019-11-22
                • 1970-01-01
                • 2011-08-02
                • 2017-11-25
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多