|
|
 geert van bommel | 2010-03-01 20:04:02 |
Hi,
very good article! I have been playing around with php/mongodb as well. Unfortunately I haven't found how to use a regular expression to find records. Or a simple %bar% (like the SQL rlike equivalent) even. I see examples in other languages, just not in php. Do you happen to know how it's done?
Looking forward to your mongo classes!
Best,
Geert |
 Cesar D. Rodas | 2010-03-01 21:52:57 - In reply to message 1 from geert van bommel |
Hello,
I forgot to mention this in the Post, thanks for asking.
With PHP you can represent most of data types supported by MongoDB, integers, floats numbers, strings, arrays, nested arrays and so forth, but they are some data type that can't be represented, here is the list:
http://www.php.net/manual/en/mongo.types.php
In the blog post I already used MongoCode to send javascript code to Map/Reduce.
In order to use Regex, you simple need to create a MongoRegex object:
http://www.php.net/manual/en/class.mongoregex.php
Regular expressions follows this format "/<regex>/<flags>", and it is evaluated at the server. In my local tests, if the regexp contains an error the query returns an empty cursor, beware with this.
The equivalent request to the SQL statement username LIKE '%bar%' is this:
<?php
$filter = array(
'username' => new MongoRegex("/.*bar.*/i"),
);
$collection->find($filter);
?>
Be careful using Regex, most of the times it can't use indexes, so it will perform a data scan, therefore it is a good idea to limit the number of documents to analyze:
<?php
$filter = array(
'username' => new MongoRegex("/.*bar.*/i"),
/* I assume that 'Karma' has an index */
'karma' => array('$gt' => 10),
);
$collection->find($filter);
?>
With Regex you can do really complex queries like this:
<?php
$filter = array(
'username' => new MongoRegex("/[a-z][a-z0-9\_]+(\_[0-9])?/i"),
/* I assume that 'Karma' has an index */
'karma' => array('$gt' => 10),
);
$collection->find($filter);
?>
I hope it clarified your doubt,
Regards, |
 geert van bommel | 2010-03-02 15:05:15 - In reply to message 2 from Cesar D. Rodas |
Hello,
excellent! That answers my question. Boy, mongodb sure is powerful and you seem to know everything about it! :-)
Thank you very much.
Best,
Geert |
 Wayne Rademan | 2012-02-03 08:07:31 - In reply to message 2 from Cesar D. Rodas |
I found the following useful when trying to do searches on multiple fields or a collection:
$host = 'localhost';
$conn = new Mongo($host);
$db = $conn->DBName;
$collection = $db->CollectionName;
$regexObj = new MongoRegex("/$search_term/i");
$where = array( '$or' => array(array( "Name" => $regexObj), array("image.caption.text" => $regexObj), array("image.user.username" => $regexObj)));
$cursor = $collection->find($where);
// Parsing the results
while ($cursor->hasNext())
{
$obj = $cursor->getNext();
$profile_image = $obj['image']['user']['profile_picture'];
echo $profile_image;
}
Hope this helps someone. |
|