windows下cmd切换到laravel项目目录使用如下命令,用composer引入mongodb。
composer require jenssegers/mongodb #

在config文件夹下的app.php中追加代码。
Jenssegers\Mongodb\MongodbServiceProvider::class, #providers数组追加
'Mongo' => Jenssegers\Mongodb\MongodbServiceProvider::class,#aliases数组追加


同样config文件夹下的database.php中,connections追加mongodb配置

vendor下增删改查等方法

#mongo测试方法
#查询
public function mongoList(){
$model = \DB::connection('mongodb')->collection('test'); #链接mongodb的test集合
$res = $model->get(); #获取集合所有文档
dd($res);
}
#添加
public function mongoAdd(){
$model = \DB::connection('mongodb')->collection('test'); #链接mongodb的test集合
$data = ['name'=>'root','age'=>18];
$res = $model->insert($data); #插入集合文档,数组形式传递参数
dd($res);
}
#编辑
public function mongoEdit(){
$model = \DB::connection('mongodb')->collection('test'); #链接mongodb的test集合
$data = ['name'=>'root','age'=>18];
$where = ['name'=>'admin'];
$res = $model->update($data,$where); #更新集合文档,数组形式传递参数
dd($res);
}
#删除
public function mongoDel(){
$model = \DB::connection('mongodb')->collection('test'); #链接mongodb的test集合
$res = $model->where(['name'=>'rad'])->delete(); #根据条件删除文档
dd($res);
}
查

controller调用model操作mongodb
<?php
namespace App\Http\Models;
use Mongo;
use DB;
class Mongodb extends Mongo {
public const CONNECTION = 'mongodb';#连接mongodb
public const COLLECTION = 'test'; #集合名称
public static function test() {
$test = DB::connection(self::CONNECTION)->collection(self::COLLECTION)->get();#获取集合文档
return $test;
}
}
#####
use App\Http\Models\Mongodb; #控制器中使用mongodb
public function mongo(){
$res = Mongodb::test();
dd($res);
}
网友评论