搜索不在mongo db php中工作

时间:2018-04-06 10:06:15

标签: mongodb mongodb-query mongodb-php php-mongodb

我在mongo db中有一个像

这样的集合
        "_id": ObjectId("5aa662b0d2ccda095400022f"),
        "EmployeeNumber": "12345",
        "JobTitle": ObjectId("5a7c2008d2ccda04d000606f"),
        "Instructor": NumberInt(1),
        "Department": ObjectId("5a8173e6d2ccda13240015a4"),
        "FirstName": "Aasiya",
        "MiddleName": "Rashid",
        "LastName": "Khan"

我正在尝试使用以下代码行搜索一个参数

       $param = preg_replace('!\s+!', ' ', $this->searchCriteria);
  $arg = trim($param);

   var_dump($arg);

    $cursor= $this->collection->aggregate(
        array(
            array(
                      '$project' => array(
                      'FullName' => array('$concat' => array('$FirstName',  ' ',  '$MiddleName', ' ', '$LastName')),
                      'FirstMiddle' => array('$concat' => array('$FirstName',  ' ',  '$MiddleName')),
                      'FirstLast' => array('$concat' => array('$FirstName',  ' ',  '$LastName')),
                      'Employee' => '$$ROOT'
                  )
                ),
             array(
               '$match' =>
                     array('$or' =>
                        array(
                        array("Employee.FullName" => new MongoRegex("/$arg/i")),
                        array("Employee.FirstLast" => new MongoRegex("/$arg/i")),
                        array("Employee.FirstMiddle" => new MongoRegex("/$arg/i")),
                        array("Employee.EmployeeNumber" => new MongoRegex("/^$arg/i"))
                          )
                        )
                      ),
                    )
                 );

     return $cursor->toArray();

返回空数组,如“array(0){}”。我在早期版本的mongo db中尝试了类似的东西,上面的查询工作正常。现在我是mongo db 3.6,它在这个版本中不起作用。如果我在参数searchCriteria中给出“aa”,它就不起作用。

请帮助!!!

1 个答案:

答案 0 :(得分:1)

最后一个阶段应该是

         array(
           '$match' =>
                 array('$or' =>
                    array(
                    array("FullName" => new MongoDB\BSON\Regex($arg, 'i')),
                    array("FirstLast" => new MongoDB\BSON\Regex($arg, 'i')),
                    array("FirstMiddle" => new MongoDB\BSON\Regex($arg, 'i')),
                    array("Employee.EmployeeNumber" => new MongoDB\BSON\Regex($arg, 'i'))
                      )
                    )
                  ),