How to make “LIKE” query work in MONGODB using PHP

2019-02-09 23:45发布

I have a list of street names and I want to select all that start with "Al". In my mysql I would do something like

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

How about mongodb using php?

标签: php mongodb like
6条回答
叼着烟拽天下
2楼-- · 2019-02-10 00:14

here is my working example:

<?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
查看更多
混吃等死
3楼-- · 2019-02-10 00:18

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

or, similar,

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

You're looking for something that contains "Al" somewhere (SQL's '%' operator is equivalent to regexps' '.*'), not something that has "Al" anchored to the beginning of the string.

查看更多
聊天终结者
4楼-- · 2019-02-10 00:25
<?php
$mongoObj = new MongoClient();
$where = array("name" => new MongoRegex("^/AI/i"));
$mongoObj->dbName->collectionName->find($where);
?>

View for more details

查看更多
贼婆χ
5楼-- · 2019-02-10 00:32

MongoRegex has been deprecated.
Use MongoDB\BSON\Regex

$regex = new MongoDB\BSON\Regex ( '^A1');
$cursor = $collection->find(array('street_name' => $regex));
//iterate through the cursor
查看更多
男人必须洒脱
6楼-- · 2019-02-10 00:37

Use a regular expression:

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

or:

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

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

Turning this into PHP:

$regex = new MongoRegex("/^Al/i");
$collection->find(array('street_name' => $regex));
查看更多
贼婆χ
7楼-- · 2019-02-10 00:41

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

Also, highly recommend just using the native mongodb connector from PHP instead of a wrapper. It's way faster than any wrapper.

http://php.net/class.mongodb

查看更多
登录 后发表回答