Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP + Mongodb concat function throwing erros

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,

like image 276
Sunil Kumar Avatar asked Apr 20 '26 01:04

Sunil Kumar


1 Answers

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'),
                             )
                          )
                      )
                    );
                });
like image 183
Somnath Muluk Avatar answered Apr 21 '26 18:04

Somnath Muluk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!