MongoRegex并在集合中搜索多行

时间:2012-07-01 11:44:43

标签: php json mongodb search

我想做的是以下内容。

$collection = $this->db->products_sale;

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

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

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

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

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

        print json_encode($who);
        $cursor = $collection->find( $who );

正如您所看到的,我正在进行多项搜索,我想做的是以下我需要能够搜索关键字,标题,说明

现在我可以做一些我认为我在做的搜索,但显然不是。从我得到的,似乎它发送一个长字符串ARRAY或JSON回到mongoDB,不像MySQL,你可以进行OR / AND搜索甚至MATCH搜索似乎MongoDB不那么聪明。

这是我发现的作品,但它会搜索搜索搜索的确切方式,例如

“windows phone 7”会被搜索而不是关键字。

$cursor = $collection->find( 
        array('$or' => array(
        array("keywords" => new MongoRegex( "/$user_query/i" )),
        array("product" => new MongoRegex( "/$user_query/i" )),
        array("description" => new MongoRegex( "/$user_query/i" )),
        )));

1 个答案:

答案 0 :(得分:0)

对于任何想知道我最终如何让它发挥作用的人。这很简单。我还在努力,但到目前为止我已经做到了。

$collection = $this->db->products_sale;

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

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

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

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

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

    //print json_encode($who);
    $cursor = $collection->find( 
    array('$or' => array($who
    )));


    if ($cursor->count() > 0)
    {
    //print "found you";
    $test = array();
    // iterate through the results
    while( $cursor->hasNext() ) {   
        $test[] = ($cursor->getNext());
    }
    print json_encode($test);