3

Mongodb + php : I am very new to mongodb, Here my requirement is that I need to keyword search on two fields (i.e first_name, last_name) and return exact matched records as username in single query.

code:

$res = $this->db->nf_users->aggregate({$project:{username:{$concat:["$first_name","$last_name"]}}},
                  {$match:{username:$search}}

Which encountered with the errors.

Parse error: syntax error, unexpected { in

Can anybody suggest, where it went wrong.

Thanks,

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54

1 Answers1

2
db.users.aggregate(
{
   $project:{
      username:{ $concat:["$first_name",' ',"$last_name"]}
   }
},
{
  $match :{
     username: { $regex:"abc",$options:"i"}
  }
}
)

By this you will be able to make case insensitive search

$users = $this->db->collection('nf_users')
          ->raw(function ($collection) {
              return $collection->aggregate(
                 array(
                    array(
                       '$project' => array(
                            'username' => array('$concat' => array('$first_name', ' ', '$last_name')),
                         )
                      ),
                    array(
                        '$match' => array(
                             'username' => array('$regex' => 'avi', '$options' => 'i'),
                             )
                          )
                      )
                    );
                });
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
  • Thnq Somnath for quick response, But I am still encounter with that parse error. – Sunil Kumar Dec 22 '15 at 11:06
  • $this->db->nf_users->aggregate( { $project:{ username:{ $concat:["$first_name",' ',"$last_name"]} } }, { $match :{ username: { $regex: $search,$options:"i"} } } ); – Sunil Kumar Dec 22 '15 at 11:06
  • @SunilKumar: Updated answer. I don't know which mongo library you are using. I changed with raw query. It works well. Keep mongo variable in single quotes and PHP variables in double quotes. – Somnath Muluk Dec 22 '15 at 11:18
  • $this->mC = new MongoClient(); $this->db = $this->mC->dbname; I am not sure, this is the object creation for our project, apart we are not using any api, – Sunil Kumar Dec 22 '15 at 11:43
  • Thnq Somanath, I made the changes with your code, It perfectly working fine. Thanking you so much. $collection->aggregate(array( array('$project' => array( 'username' => array('$concat' => array('$first_name', ' ', '$last_name')), ) ), array( '$match' => array( 'username' => array('$regex' => $search, '$options' => 'i'), ) ) ) ); – Sunil Kumar Dec 22 '15 at 11:49