【发布时间】:2011-04-27 00:44:33
【问题描述】:
我有一个街道名称列表,我想选择所有以“Al”开头的名称。 在我的 MySQL 中,我会做类似的事情
SELECT * FROM streets WHERE "street_name" LIKE "Al%"
MongoDB 使用 PHP 怎么样?
【问题讨论】:
我有一个街道名称列表,我想选择所有以“Al”开头的名称。 在我的 MySQL 中,我会做类似的事情
SELECT * FROM streets WHERE "street_name" LIKE "Al%"
MongoDB 使用 PHP 怎么样?
【问题讨论】:
使用正则表达式:
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));
【讨论】:
见:http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart
另外,强烈建议只使用 PHP 中的本机 mongodb 连接器,而不是包装器。它比任何包装器都快。
【讨论】:
这是我的工作示例:
<?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
【讨论】:
$collection.find({"name": /.*Al.*/})
或者,类似的,
$collection.find({"name": /Al/})
您正在寻找某处包含“Al”的内容(SQL 的 '%' 运算符等效于正则表达式''.*'),而不是在字符串开头锚定“Al”的内容。
【讨论】:
MongoRegex 已被弃用。
使用MongoDB\BSON\Regex
$regex = new MongoDB\BSON\Regex ( '^A1');
$cursor = $collection->find(array('street_name' => $regex));
//iterate through the cursor
【讨论】:
<?php
$mongoObj = new MongoClient();
$where = array("name" => new MongoRegex("^/AI/i"));
$mongoObj->dbName->collectionName->find($where);
?>
【讨论】:
你也可以这样做
['key' => ['$regex' => '(?i)value']]
【讨论】: