Nida Amin
Nida Amin

Reputation: 755

Search not working in mongo db php

I have a collection in mongo db like

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

And I am trying to search on one parameter by using below lines of code

       $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();

It is returning empty array like "array(0) { }". I have tried something like this in earlier version of mongo db, the above query was working fine. Now I am mongo db 3.6, it is not working in this version. If I give "aa" in parameter searchCriteria, it does not work.

Please help!!!

Upvotes: 0

Views: 53

Answers (1)

Alex Blex
Alex Blex

Reputation: 37058

The last stage should be

         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'))
                      )
                    )
                  ),

Upvotes: 1

Related Questions