MongoDB

webman默认使用 jenssegers/mongodb 作为mongodb组件,它是从laravel项目中抽离出来的,用法与laravel相同。

使用jenssegers/mongodb之前必须先给php-cli安装mongodb扩展。

使用命令php -m | grep mongodb查看php-cli是否装了mongodb扩展。注意:即使你在php-fpm安装了mongodb扩展,不代表你在php-cli可以使用它,因为php-cliphp-fpm是不同的应用程序,可能使用的是不同的php.ini配置。使用命令php --ini来查看你的php-cli使用的是哪个php.ini配置文件。

安装

  1. composer require psr/container ^1.1.1 illuminate/database jenssegers/mongodb ^3.8.0

配置

config/database.php 里增加 mongodb connection, 类似如下:

  1. return [
  2. 'default' => 'mysql',
  3. 'connections' => [
  4. ...这里省略了其它配置...
  5. 'mongodb' => [
  6. 'driver' => 'mongodb',
  7. 'host' => '127.0.0.1',
  8. 'port' => 27017,
  9. 'database' => 'test',
  10. 'username' => null,
  11. 'password' => null,
  12. 'options' => [
  13. // here you can pass more settings to the Mongo Driver Manager
  14. // 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
  15. 'database' => 'admin', // required with Mongo 3+
  16. ],
  17. ],
  18. ],
  19. ];

示例

  1. <?php
  2. namespace app\controller;
  3. use support\Request;
  4. use support\Db;
  5. class User
  6. {
  7. public function db(Request $request)
  8. {
  9. Db::connection('mongodb')->collection('test')->insert([1,2,3]);
  10. return json(Db::connection('mongodb')->collection('test')->get());
  11. }
  12. }

更多内容请访问

https://github.com/jenssegers/laravel-mongodb