在Laravel中使用MongoDB

MongoDB實用場景

  • 產品用戶訪問日誌,點擊埋點統計信息
  • 業務系統環境參數配置信息
  • 業務系統運行時日誌,如laravel.lognginx.log

使用Homebrew在macoOS安裝MongoDB PHP Driver

在macOS中,MongoDB 擴展已經從Homebrew倉庫中移除,須要經過pecl安裝此擴展。php

$ sudo pecl install mongodb -v
...

Build process completed successfully
Installing '/usr/local/Cellar/php@7.2/7.2.19/pecl/20170718/mongodb.so'
install ok: channel://pecl.php.net/mongodb-1.5.4
Extension mongodb enabled in php.ini
複製代碼

在項目中,使用phpinfo() 查詢PHP擴展安裝位置。nginx

...
Configuration File (php.ini) Path	/usr/local/etc/php/7.2
Loaded Configuration File	/usr/local/etc/php/7.2/php.ini
Scan this dir for additional .ini files	/usr/local/etc/php/7.2/conf.d
Additional .ini files parsed	/usr/local/etc/php/7.2/conf.d/ext-opcache.ini, /usr/local/etc/php/7.2/conf.d/php-memory-limits.ini
....
複製代碼

按照ext-opcache.ini配置,建立一個ext-mongodb.ini文件laravel

touch /usr/local/etc/php/7.2/conf.d/ext-mongodb.ini
複製代碼

mongodb.so擴展寫入該文件sql

[mongodb]
 extension=/usr/local/Cellar/php@7.2/7.2.19/pecl/20170718/mongodb.so
複製代碼

同時在php.ini中移除mongodb.so擴展mongodb

extension="mongodb.so" // remove
extension="php_mongodb.so" // remove 
複製代碼

重啓一下PHP數據庫

sudo brew service restart --all
複製代碼

查看是否安裝成功bash

php -m|grep mongodb
複製代碼

在Laravel中使用MongoDB

使用Composer建立一個Laravel項目composer

composer create-project --prefer-dist laravel/laravel laravel-mongodb-exploer -vvv
複製代碼

成功後,再安裝Laravel-MongoDB擴展ui

composer require jenssegers/mongodb -vvv
複製代碼

按照擴展文檔說明,咱們添加一個MongoDB數據庫鏈接this

//database.php
...
'mongodb' => [
            'driver'   => 'mongodb',
            'host'     => env('MONGODB_HOST', 'localhost'),
            'port'     => env('MONGODB_PORT', 27017),
            'database' => env('MONGODB_DATABASE'),
            'username' => env('MONGODB_USERNAME'),
            'password' => env('MONGODB_PASSWORD'),
            'options'  => [
                'database' => 'admin' // sets the authentication database required by mongo 3
            ]
        ],
...
  
  
//.env
...  
MONGODB_HOST=127.0.0.1
MONGODB_PORT=27017
MONGODB_DATABASE=viewers
...
複製代碼

命令行建立MongoDB數據庫

macOS中,在命令行執行mongo開啓MongoDB Shell

./mongo
複製代碼

使用show dbs查看已有數據庫

show dbs;

admin    0.000GB
config   0.000GB
local    0.000GB
viewers  0.000GB
複製代碼

若是沒有發現viewers,則建立該數據庫。注意只有viewers中存在collection時, 上面結果纔會顯示viewers

use viewers;
複製代碼

使用數據庫後,須要建立colleciton

db.ad_clicks.insert({"ip":"201.35.63.14", "ad_index": 3, "created_at": "2019-06-10 11:34:12"})
複製代碼

使用find查詢記錄

> db.ad_clicks.find()
{ "_id" : ObjectId("5cf71b34e14620598643d23b"), "ip" : "201.34.46.3", "ad_index" : "2", "created_at" : "2019-06-05 11:34:53" }
{ "_id" : ObjectId("5cf71d3de14620598643d23d"), "ip" : "200.14.145.64", "ad_index" : 1, "created_at" : "2019-06-04 11:11:45" }
{ "_id" : ObjectId("5cf71d3ee14620598643d23e"), "ip" : "200.14.145.64", "ad_index" : 1, "created_at" : "2019-06-04 11:11:45" }
{ "_id" : ObjectId("5cf71d44e14620598643d23f"), "ip" : "200.14.145.64", "ad_index" : 1, "created_at" : "2019-06-04 11:11:45" }
{ "_id" : ObjectId("5cf71d45e14620598643d240"), "ip" : "200.14.145.64", "ad_index" : 1, "created_at" : "2019-06-04 12:34:12" }
{ "_id" : ObjectId("5cfe28823316506991c41786"), "ip" : "201.35.63.14", "ad_index" : 3, "created_at" : "2019-06-10 11:34:12" }
複製代碼

在Laravel DB中查詢MongoDB

使用了Laravel-MongoDB擴展,能夠基於Eloquent與Query Builder操做MySQL同樣的數據php artisan thinker

查詢ad_clicks集合全部記錄

DB::connection('mongodb')->table('ad_clicks')->get()
複製代碼

查詢單個記錄

DB::connection('mongodb')->collection('ad_clicks')->find('5cf71b34e14620598643d23b')
複製代碼

修改某個記錄

DB::connection('mongodb')->collection('ad_clicks')->where('_id', '5cf71b34e14620598643d23b')->update(['ad_index'=>2]);
複製代碼

在Laravel ORM中查詢MongoDB

在項目中,建立一個Model

php artisan make:model Models/AdClick
複製代碼

修改繼承父類和數據庫鏈接,AdClick.php

...
use Jenssegers\Mongodb\Eloquent\Model;

class AdClick extends Model {
    protected $connection = 'mongodb';
  
  	/** * The attributes that are mass assignable. * * @var array */
    protected $fillable = [];

    /** * The attributes that aren't mass assignable. * * @var array */
    protected $guarded = [];
}
複製代碼

繼續在Thinker中,插入數據

App\Models\AdClick::create(['ip' => '31.42.4.14', 'ad_index' => 4, 'created_at' => '2019-06-10 18:10:01', 'ip2long' => ip2long('31.42.4.14')]);
複製代碼

統計訪問數據

App\Models\AdClick::where('ip', '31.42.4.14')->count()
複製代碼
相關文章
相關標籤/搜索