开发者

I need to use a like query in mongo php

开发者 https://www.devze.com 2023-02-11 10:29 出处:网络
I have used this query in shell. It worked fine. If I use it in php, it shows me an error <?php $m = new Mongo();

I have used this query in shell. It worked fine. If I use it in php, it shows me an error

<?php
$m = new Mongo();
$db = $m->foo;
$collection = $db->base;
$query = array( "ro" => '/^a/' );
$cursor = $collecti开发者_Go百科on->find($query);

foreach ($cursor as $obj) {
    echo $obj["ro"] . "<br/>";
}

I am not sure, will db.base.find({"ro": /^a/}).limit(10); query work in php??


You need to use MongoRegex() ...

See docs here: http://php.net/manual/en/class.mongoregex.php

So the PHP code would be something like ...

$regex = new MongoRegex("/^a/"); 
$where = array('ro' => $regex);
$cursor = $collection->find($where);


If you use mongodb extension, you should use MongoDB\BSON\Regex() instead of MongoRegex()

$regex = new \MongoDB\BSON\Regex("^a"); 
$where = array('ro' => $regex);
$cursor = $collection->find($where)

You Don't have to use "/" [regex] "/". Just the regex works fine


In one line:

$mCollection->find(array("date" => new MongoRegex("/2011-10-25/")));
0

精彩评论

暂无评论...
验证码 换一张
取 消