SoFunction
Updated on 2025-03-10

Example of method using MongoDB in Laravel

MongoDB practical scenarios

  • Product user access log, click to bury the statistical information
  • Business system environment parameter configuration information
  • Business system runtime log, such as

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

$ sudo pecl install mongodb -v
...

Build process completed successfully
Installing '/usr/local/Cellar/[email protected]/7.2.19/pecl/20170718/'
install ok: channel:///mongodb-1.5.4
Extension mongodb enabled in 

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

...
Configuration File () Path  /usr/local/etc/php/7.2
Loaded Configuration File  /usr/local/etc/php/7.2/
Scan this dir for additional .ini files  /usr/local/etc/php/7.2/
Additional .ini files parsed  /usr/local/etc/php/7.2//, /usr/local/etc/php/7.2//
....

Create a file by configuration

touch /usr/local/etc/php/7.2//

Write the extension to the file

 [mongodb]
 extension=/usr/local/Cellar/[email protected]/7.2.19/pecl/20170718/

Remove the extension at the same time

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

Restart PHP

sudo brew service restart --all

Check if the installation is 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

Following the extension documentation instructions, we add a MongoDB database connection

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

Create MongoDB database on the command line

In macOS, execute mongo on the command line to enable 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 no views are found, the database is created. Note that only when the collection exists in the views, the above results will show the views.

use viewers;

After using the database, you need to create a collection

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

Use find to query records

> 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 MySQL-like data based on Eloquent and Query Builder php artisan thinker

Query all records in the ad_clicks collection

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

Query a single record

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 class and database connection,

...
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 to insert data in 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')]);

Statistical access data

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

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.