Info
Installation
Setting
設定可連入的 ip 與 port
- MongoDB 預設只開放給 localhost,必須修改設定檔
sudo vi /etc/mongod.conf
net:
port: 27017
# 0.0.0.0 對所有 ip 開放
bindIp: 0.0.0.0
# 重新啟動
sudo service mongod restart
建立權限
- MongoDB 預設沒有權限,不需要登入帳號密碼即可操作資料
- 如果需要建立權限,必須先建立管理者(admin DB 的 Users)
# 進入 mongo
mongo
# 進入 admin DB
use admin
# 建立管理者,回覆 Successfully added user: 表示成功
db.createUser(
{
user: "帳號",
pwd: "密碼",
roles: [ { role: "root", db: "admin" } ]
}
)
# 使用管理者權限,回覆 1 表示成功
db.auth("帳號", "密碼");
mongo -u "帳號" -p "密碼" --authenticationDatabase "admin"
預設開啟帳號驗證
sudo vi /etc/mongod.conf
#security:
security.authorization: enabled
# 重新啟動
sudo service mongod restart
Management Tool
PHP Driver
phpbrew
# PHP 7.0 以上
phpbrew ext install mongodb
原生 php
# 根據主機使用的 PHP 版本選擇安裝 dev 版本
sudo apt install php-pear php7.1-dev
# 更新 pecl
sudo pecl channel-update pecl.php
# 安裝 mongodb
sudo pecl install mongodb
Build process completed successfully
Installing '/usr/lib/php/20160303/mongodb.so'
install ok: channel://pecl.php.net/mongodb-1.3.0
configuration option "php_ini" is not set to php.ini location
You should add "extension=mongodb.so" to php.ini
- 新增至 php.ini(apache & cli)
sudo vi /etc/php/7.1/apache2/php.ini
sudo vi /etc/php/7.1/cli/php.ini
;extension=php_xsl.dll
extension=mongodb.so
Laravel Package
- /project/config/database.php
// mongodb
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGODB_HOST'),
'port' => env('MONGODB_PORT'),
'database' => env('MONGODB_DATABASE'),
'username' => env('MONGODB_USERNAME'),
'password' => env('MONGODB_PASSWORD'),
'options' => [
'database' => env('MONGODB_DATABASE'),
]
],
// 需要指定連線與集合
$r = DB::connection('mongodb')->collection(MONGODB_COLLECTION_NAME)->get();
dd($r);
- Model
- /project/App/Models/Mongo/Test.php
<?php
namespace App\Models\Mongo;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Test extends Eloquent
{
/**
* guarded attributes
*
* @var array
*/
protected $guarded = [];
/**
* collection name
*
* @var string
*/
// protected $collection = 'tests';
/**
* connection name
*
* @var string
*/
protected $connection = 'mongodb';
}
// 跟一般 model 使用沒有差別
$r = $this->model->where('time', '=', '2017-09-14 19:21')->take(3)->get();
dd($r);
Reference
-
-
-