1

我已将正则表达式保存为集合中的值。我想根据 mongodb 中的正则表达式检查一个字符串,它是否匹配?我知道我应该使用相同的javascript代码,但它不适用于php-mongodb。

它从 mongodb 客户端控制台工作。

这里我的代码,

<?php

    $dbName = "XYZ";
    try
    {
            $dbInstanceName = $dbName;
            $mongoInstance  = new Mongo("localhost:27017", array("persist"    => "x"));
            $dbReference = $mongoInstance->$dbInstanceName;
            $db          = $mongoInstance->$dbInstanceName;
    }
    catch (Exception $e)
    {
            echo "<pre>";
            print_r($e);
            echo "</pre>";
            exit;
    }

    $query  = new MongoCode("function (){return RegExp(this.regCountry).test('India');}");

    $c = "Countries1";

    $cursor = $db->$c->find($query);


    if ($cursor->count() == 0)
    {
            echo "<pre>";
            print_r("No Data Found.!");
            echo "</pre>";
            exit;
    }
    else
    {

            $data = array();
            while ($cursor->hasNext())
            {
                    $cursor->next();
                    array_push($data, $cursor->current());
            }                
    }
    echo "<pre>";
    print_r($data);
    echo "</pre>";
    exit;

?>

它的工作,但没有返回......!

共鸣:

Array
(

)

在这里,控制台屏幕排序,它给定的返回一个值。

在此处输入图像描述

这是我的数据样本:

在此处输入图像描述

怎么了?

4

2 回答 2

0

如果我上面的评论不起作用,请尝试更改:

$cursor = $db->$c->find($query);

到:

$cursor = $db->selectCollection($c)->find($query);
于 2012-07-24T13:40:40.910 回答
0

最后我得到了答案:

更改我的代码如下所示

<?php

    $dbName = "Scrubly";
    try
    {
            $dbInstanceName = $dbName;
            $mongoInstance  = new Mongo("localhost:27017", array("persist"    => "x"));
            $dbReference = $mongoInstance->$dbInstanceName;
            $db          = $mongoInstance->$dbInstanceName;
    }
    catch (Exception $e)
    {
            echo "<pre>";
            print_r($e);
            echo "</pre>";
            exit;
    }

    $query = "function(){return db.Countries1.find(function (){return RegExp(this.regCountry).test('India');}).toArray();}";

    $result = $db->execute($query);
    echo "<pre>";
    print_r($result);
    echo "</pre>";
    exit;

?>

输出 :

Array
(
[retval] => Array
    (
        [0] => Array
            (
                [_id] => MongoId Object
                    (
                        [$id] => 500e5b456bcb44780d000072
                    )

                [country] => India
                [countryCode] => IN
                [createdAt] => 2012-07-24 13:52:29
                [id] => 386
                [regCountry] => ^(.*)India(.*)$
                [updatedAt] => 2012-07-24 13:52:29
            )

    )

[ok] => 1
)
于 2012-07-25T07:22:38.290 回答