Using MongoDB in Laravel

MongoDB utility scenarios

  • Product user access log, click buried statistical information
  • Business System Environment Parameter Configuration Information
  • Business system runtime logs, such as laravel.log, nginx.log

Install MongoDB PHP Driver on macoOS using Homebrew

In macOS, the MongoDB extension has been removed from the Homebrew repository and needs to be installed through pecl.

$ 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

In your project, use phpinfo() to query the PHP extension installation location.

...
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
....

Create an ext-mongodb.ini file as configured by ext-opcache.ini

touch /usr/local/etc/php/7.2/conf.d/ext-mongodb.ini

Write the mongodb.so extension to the file

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

Remove the mongodb.so extension from php.ini

extension="mongodb.so" // remove
extension="php_mongodb.so" // remove 

Restart PHP

sudo brew service restart --all

Check to see if the installation was successful

php -m|grep mongodb

Using MongoDB in Laravel

Create a Laravel project using Composer

 composer create-project --prefer-dist laravel/laravel laravel-mongodb-exploer -vvv

After success, install the Laravel-MongoDB extension

composer require jenssegers/mongodb -vvv

Follow the extended documentation to add a MongoDB database connection

//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
...

Command Line Create MongoDB Database

In macOS, execute mongo on the command line to open the MongoDB Shell

./mongo

Use show dbs to view existing databases

show dbs;

admin    0.000GB
config   0.000GB
local    0.000GB
viewers  0.000GB

If viewers are not found, the database is created.Note that the above results only show viewers if a collection exists in the viewers

use viewers;

After using the database, you need to create a colleciton

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

Query records using 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" }

Query MongoDB in Laravel DB

Using the Laravel-MongoDB extension, you can operate on the same data php artisan thinker as MySQL based on Eloquent and Query Builder

Query all records of ad_clicks collection

DB::connection('mongodb')->table('ad_clicks')->get()

Query individual records

DB::connection('mongodb')->collection('ad_clicks')->find('5cf71b34e14620598643d23b')

Modify a record

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

Query MongoDB in Laravel ORM

In the project, create a Model

php artisan make:model Models/AdClick

Modify inherited parent and database connections, 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 = [];
}

Continue in Thinker, insert data

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')]);

Statistical Access Data

App\Models\AdClick::where('ip', '31.42.4.14')->count()

Keywords: Database MongoDB PHP Laravel

Added by bigfatpig on Sun, 10 Nov 2019 07:08:02 +0200