MongoDB
Webman uses mongodb/laravel-mongodb as the MongoDB component by default, which is extracted from the Laravel project and operates the same way as Laravel.
Before using jenssegers/mongodb
, you must install the MongoDB extension for php-cli
.
Note
This manual is for webman v2. If you are using webman v1, please refer to the v1 manual.
Use the commandphp -m | grep mongodb
to check if the MongoDB extension is installed forphp-cli
. Note: Installing the MongoDB extension forphp-fpm
does not mean it will be available inphp-cli
, asphp-cli
andphp-fpm
are different applications and may use differentphp.ini
configurations. Use the commandphp --ini
to see whichphp.ini
configuration file yourphp-cli
is using.
Installation
composer require -W webman/database mongodb/laravel-mongodb ^4.8
After installation, you need to restart (reload will not work).
Configuration
Add a mongodb
connection to config/database.php
, similar to the following:
return [
'default' => 'mysql',
'connections' => [
...other configurations are omitted...
'mongodb' => [
'driver' => 'mongodb',
'host' => '127.0.0.1',
'port' => 27017,
'database' => 'test',
'username' => null,
'password' => null,
'options' => [
// here you can pass more settings to the Mongo Driver Manager
// see https://www.php.net/manual/en/mongodb-driver-manager.construct.php under "Uri Options" for a list of complete parameters that you can use
'appname' => 'homestead'
],
],
],
];
Example
<?php
namespace app\controller;
use support\Request;
use support\Db;
class UserController
{
public function db(Request $request)
{
Db::connection('mongodb')->table('test')->insert([1,2,3]);
return json(Db::connection('mongodb')->table('test')->get());
}
}
Model Example
<?php
namespace app\model;
use DateTimeInterface;
use support\MongoModel as Model;
class Test extends Model
{
protected $connection = 'mongodb';
protected $table = 'test';
public $timestamps = true;
/**
* @param DateTimeInterface $date
* @return string
*/
protected function serializeDate(DateTimeInterface $date): string
{
return $date->format('Y-m-d H:i:s');
}
}