美文网首页
Laravel-mongodb

Laravel-mongodb

作者: 可望不可j | 来源:发表于2021-05-29 09:53 被阅读0次

推荐组件:composer require jenssegers/mongodb

注册服务:Jenssegers\Mongodb\MongodbServiceProvider::class,

添加Facades : 'Mongo' => Jenssegers\Mongodb\MongodbServiceProvider::class,

修改数据库配置文件 config/database.php 中

添加 MongoDB 的数据库的信息:

'mongodb' => [   

        'driver'  => 'mongodb',   

        'host'    => 'localhost',   

        'port'    => 27017,   

        'database' => 'mydb',   

        'username' => '',   

        'password' => '',

],

'default' => env('DB_CONNECTION', 'mysql'),

改成:

'default' => env('DB_CONNECTION', 'mongodb'),

使用方法:

/**

* Redis

*/

namespace App\Models;

use Illuminate\Support\Facades\DB;

class Mongodb

{

/**

    * 使用此数据库配置

*/

    protected static $connection = 'mongodb';

/**

    * 写入数据

*/

    public static function insert($table,$data){

            return DB::connection(static::$connection)->collection($table)->insert($data);

    }

    public static function delete($table,$where){

            return DB::connection(static::$connection)->collection($table)->where($where)->delete();

    }

    public static function update($table,$where,$update){

            return DB::connection(static::$connection)->collection($table)->where($where)->update($update);

    }

/**

    * 追加更新

*/

    public static function pushArr($table,$where,$field,$update){

        return DB::connection(static::$connection)->collection($table)->where($where)->push($field,$update);

    }

/**

    * 分页查询

*/

    public static function paginate($table,$whereField=[],$where=[],$page=1,$pageSize=10,$orderBy=[]){

            $collection= DB::connection(static::$connection)->collection($table);

            if($where){

                    $collection= $collection->where($where);

            }

            if($whereField){

                    $collection= $collection->select($whereField);

            }

            $count= $collection->count();

            $list= [];

            if( $count> 0 ){

                    if($orderBy){

                            foreach($orderBy as $field=>$sort){

                                $collection= $collection->orderBy($field, $sort);

                            }

                    }

                    $offset= $pageSize*($page-1);

                    $collection= $collection->offset($offset)->limit($pageSize)->get();

                    foreach($collectionas $record){

                        $list[]= $record;

                    }

            }

return [  'count'=> $count, 'list'=> $list];

}

/**

    * 查询

    * @param $table

    * @param array $where

    * @param array $orderBy

    * @return array[]

*/

    public static function getDataAll($table,$field=[],$where=[],$orderBy=[]){

                $collection= DB::connection(static::$connection)->collection($table);

                $list= [];

                if($field){

                    $collection= $collection->select($field);

                }

                if($where){

                    $collection= $collection->where($where);

                }

                if($orderBy){

                        foreach($orderBy as $field=>$sort){

                                $collection= $collection->orderBy($field, $sort);

                        }

                }

                 $collection= $collection->get();

                 foreach($collectionas $record){

                            $list[]= $record;

                    }

                return $list;

                }

}

特别操作:

超时

要防止MongoCursorTimeout异常,您可以手动设置将应用于游标的超时值:

DB::collection('users')->timeout(-1)->get();

Upsert是一种特殊的更新方式,要是没有找到符合条件的文档,则会自动创建一个文档,否则更新对应的文档数据。

看 mongodb权威指南提到 upsert会避免竞态问题,如果使用日常的思维去考虑这个问题,需要先去数据库中查找符合条件的文档,然后再根据更新信息更新数据,这个在多线程或者多进程的情况下产生资源竞争的情况,使用 upsert可以很好的避免这种情况的发

DB::collection('users')->where('name', 'John')->update($data, ['upsert' => true]);

Projections(投影文档)

您可以使用项目方法将投影应用于查询。

value字段的取值为0或者false时,表示要在返回结果中去除该字段;如果value字段取值为1或者true,表示在返回结果中需要包含这个字段。

查询结构只展示title和likes

$project = ['title'=>1,'likes'=>1,"_id"=>0];

DB::collection('users')->project($project)->get();

DB::collection('items')->project(['tags' => ['$slice' => 1]])->get();

DB::collection('items')->project(['tags' => ['$slice' => [3, 7]]])->get();

分页使用

$limit = 25;

$projections = ['id', 'name'];

DB::collection('items')->paginate($limit, $projections);

Push(更新数组$push操作符)

$push操作符添加指定的值到数组中,$push操作符有如下的格式:

DB::collection('users')->where('name', 'John')->push('items', 'boots');

DB::collection('users')->where('name', 'John')->push('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);

如果您不想要重复项,请将第三个参数设置为true:

DB::collection('users')->where('name', 'John')->push('items', 'boots', true);

Pull(更新数组$pull修饰符)

$pull修饰符会删除掉数组中符合条件的元素

DB::collection('users')->where('name', 'John')->pull('items', 'boots');

DB::collection('users')->where('name', 'John')->pull('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);

Unset(删除一个指定的字段)

如果指定的字段不存在则操作不做任何处理;

当使用$操作符匹配任何数组元素,$unset替换指定的元素为null而不是删除掉指定的元素,此行为保持数组大小和位置一直;

从文档中删除一个或多个字段。

DB::collection('users')->where('name', 'John')->unset('note');

您还可以在模型上执行取消设置。

$user = User::where('name', 'John')->first();

$user->unset('note');

查询缓存

您可以使用remember方法轻松缓存查询结果:

$users = User::remember(10)->get()

相关文章

网友评论

      本文标题:Laravel-mongodb

      本文链接:https://www.haomeiwen.com/subject/zfiksltx.html