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

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;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值