3

i'm trying to combine $regex and $in to do simple search.

For example I have a user query of this kind :

$user_query = "for focus red";

In my mongodb collection for each document I have a keywords field. I want to get to get the document where the field keywords is :

{
    keywords :
        [0] => ford,
        [1] => focus,
        [2] => red
}

As you can see the user has done a mistake and typed "for" instead of "ford".

I can get the results with $in if the user types Ford, but I don't know how to combine $regex and $in, I have looked the mongodb doc and php mongo doc.

2
  • What is $regex and $in? Please add the related code to your question that shows more about these variables or if it's part of a mongo query, please show the query and the code related to the query. Commented Aug 6, 2011 at 14:22
  • 5
    @hakre $in and $regex are not PHP variables, they are search operators for MongoDB queries. You're asking him to answer his own question. He said he doesn't know how to write the query. Commented Aug 6, 2011 at 14:35

2 Answers 2

5

There is my quick snippet:

$user_query = preg_replace("/[[:blank:]]+/"," ", $user_query);
$arr_query = explode(' ', $user_query);

if (count($arr_query) > 1) {
    $tmp = array();

    foreach ($arr_query as $q) {
        $tmp[] = new MongoRegex( "/". $q ."/" );
    }

    $who['keywords'] = array('$in' => $tmp);

} else {
    $who['keywords'] = new MongoRegex( "/". $user_query ."/" );
}

$db->collection->find( $who );
Sign up to request clarification or add additional context in comments.

1 Comment

btw, you can replace $in with $all to narrow sesults
0

I'm not using Mongo with PHP but i would do like this: (i'm using mongo shell syntax)

//find everything inside test that was either written by someone or text contains the word "and"
db.test.find( { $or : [ { "keywords" : { $in: ["Ford"] } } , { "keywords" : { $regex: "for.*" } } ] } )

I'm sure you can translate in into the proper PHP structure.

2 Comments

The use of $or is interesting, however this is not my issue. THe question is about $regex, here you are only answering for one keyword not all the query.
@Flyingbeaver You can add as many keywords as needed. These are just arrays (in Mongo as well as in PHP) so you could write $in: ["Ford", "focus", "red"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.