qiuxis 2016-10-24 22:33:33 9328次浏览 1条评论 3 0 0

mongdb 的安装和 扩展的安装这些都有,但是安装好后如何去实用 YII2 mongdb 扩展却很少有相关文章说明,在此做下记录。

一、条件
1、LINUX 系统安装 mongodb (这里mongodb 的PHP 扩展选择最新的安装,如果PHP版本是7.0 选择MongoDB 而不是 Mongo)
2、安装YII2 的 mongodb 扩展
本人安装版本为:mongodb version v3.2.9 ,php version PHP 7.0.10

二、条件满足后测试
显示 mongodb 下的 DB

> show dbs
local  0.000GB
customer   0.000GB

切换到 db test, 并创建 db test 的用户归类到角色 dbAdmin 组中

> use customer 
> db.createUser(
   {
     user: "accountUser",
     pwd: "password",
     roles: [ "readWrite", "dbAdmin" ]
   }
)

增加了DB admin (只要创建了用户自动就增加了 db admin)

> show dbs
admin  0.000GB
local  0.000GB
customer   0.000GB

返回到YII2
/common/config/main-local.php
添加配置信息

'components' => [
...
        'mongodb' => [
            'class' => '\yii\mongodb\Connection',
            'dsn' => 'mongodb://accountUser:password@localhost:27017/customer',
        ],
...
];	

/frontend/controllers/SiteController.php

...
    public function actionIndex()
    {
        $collection = Yii::$app->mongodb->getCollection ( 'customer' );
        $res = $collection->insert ( [
            'name' => 'John Smith22',
            'status' => 2
        ] );
        var_dump($res);
        return $this->render('index');
    }
...

打开页面,运行

返回终端

> show collections
customer

> db.customer.find()
{ "_id" : ObjectId("580b3d4be13823434a7a5032"), "name" : "John Smith22", "status" : 2 }

测试完毕,YII2 成功实用 mongodb 扩展。

  • 评论于 2018-01-05 10:23 举报

    不需要配置用户名和密码的吗
    `
    'db_mongodb_sxmj_h5' => [

            'class' => '\yii\mongodb\Connection',
            'dsn' => 'mongodb://@localhost:27017/game_db',
            'options' => [
                "username" => "admin",
                "password" => "admin"
            ]
        ],
    

    `

您需要登录后才可以评论。登录 | 立即注册