Yii2中连接mongoDb以及基础的查询

来源:互联网 发布:发射后不管知乎 编辑:程序博客网 时间:2024/05/22 10:45

1、检查php环境是否已经扩展了mongodb,php - m | grep mongodb,如果没有,接下来扩展mongodb,详见:http://www.runoob.com/mongodb/mongodb-install-php-driver.html


2、添加mongoDB连接的配置:

'components' =>array(
'mongodb' => [
'class' => 'yii\mongodb\Connection',
'dsn' => 'mongodb://username:password@host:27017/admin',
],
)

3、在代码中使用mongo的基本查询

$db = \Yii::$app->get('mongodb');

$query = new  yii\mongodb\Query();
$data = $query->select(['colName'])
->from(['dataBaseName','tableName'])

->where(['colName' => "XXXX"])

->all();

如果有去重需求的话,将->all()换成 ->distinct('colName',$db);

这里from的参数既可以是字符串又可以是数据,当参数是字符串的时候当做集合(collection类似mysql中的表名)处理,此时的database默认的,也就是配置中的数据库;如果传入的参数是数组的话,数组的第一个元素视作数据库名称,数组的第二个参数视作collection的名称,以下是yii\mongodb\Query文件中关于from函数的描述


/** * Sets the collection to be selected from. * @param string|array the collection to be selected from. If string considered as the name of the collection * inside the default database. If array - first element considered as the name of the database, * second - as name of collection inside that database * @return $this the query object itself. */public function from($collection){    $this->from = $collection;    return $this;}


阅读全文
0 0
原创粉丝点击