如何在MongoDB中进行“LIKE”查询工作?

时间:2011-04-27 00:44:33

标签: php sql mongodb sql-like

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

的事情
SELECT * FROM streets WHERE "street_name" LIKE "Al%"

使用PHP的MongoDB怎么样?

7 个答案:

答案 0 :(得分:14)

使用正则表达式:

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

答案 1 :(得分:3)

请参阅:http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart

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

http://php.net/class.mongodb

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

这是我的工作示例:

<?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 :(得分:0)

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

或类似的

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

你正在寻找某处包含“Al”的东西(SQL的'%'运算符等同于regexps''。*'),而不是将“Al”锚定到字符串开头的东西。

答案 5 :(得分:0)

<?php
$mongoObj = new MongoClient();
$where = array("name" => new MongoRegex("^/AI/i"));
$mongoObj->dbName->collectionName->find($where);
?>

View for more details

答案 6 :(得分:0)

您也可以这样做

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