【问题标题】:PHP + Mongodb concat function throwing errosPHP + Mongodb concat 函数抛出错误
【发布时间】:2015-12-22 10:33:20
【问题描述】:

Mongodb + php : 我对 mongodb 很陌生,这里我的要求是我需要在两个字段(即名字,姓氏)上进行关键字搜索,并在单个查询中返回完全匹配的记录作为用户名。

代码:

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

遇到的错误。

解析错误:语法错误,意外{ in

任何人都可以建议,哪里出错了。

谢谢,

【问题讨论】:

    标签: php mongodb concat


    【解决方案1】:
    db.users.aggregate(
    {
       $project:{
          username:{ $concat:["$first_name",' ',"$last_name"]}
       }
    },
    {
      $match :{
         username: { $regex:"abc",$options:"i"}
      }
    }
    )
    

    这样你就可以进行不区分大小写的搜索了

    $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'),
                                 )
                              )
                          )
                        );
                    });
    

    【讨论】:

    • Thnq Somnath 以便快速响应,但我仍然遇到该解析错误。
    • $this->db->nf_users->aggregate( { $project:{ username:{ $concat:["$first_name",' ',"$last_name"]} } }, { $match :{ username: { $regex: $search,$options:"i"} } } );
    • @SunilKumar:更新了答案。我不知道您使用的是哪个 mongo 库。我用原始查询进行了更改。它运作良好。 mongo 变量用单引号,PHP 变量用双引号。
    • $this->mC = new MongoClient(); $this->db = $this->mC->dbname;我不确定,这是我们项目的对象创建,除了我们没有使用任何 api,
    • Thnq Somanath,我对您的代码进行了更改,它运行良好。非常感谢你。 $collection->aggregate(array(array('$project' => array('username' => array('$concat' => array('$first_name', '', '$last_name')), )) , 数组( '$match' => 数组( '用户名' => 数组('$regex' => $search, '$options' => 'i'), ) ) ) );
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多