[ laravel-mongodb教程 ] laravel使用/升级/配置mongodb数据库
在前面的文章Laravel/Lumen安装配置Mongodb扩展中我们介绍了安装laravel-mongodb
拓展,接下来我们查看如何使用以及常用命令
一、升级
从版本2升级到3
在新的release
版本中支持新的mongodb PHP
扩展,我们还移动了Model
类的位置并用一个特性替换了MySQL
模型类。
请在模型文件的顶部将所有Jenssegers\Mongodb\Model
引用更改为Jenssegers\Mongodb\Eloquent\Model
或注册alias
。
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {}
如果你正在使用混合关系,使用Illuminate\Database\Eloquent\Model
代替Jenssegers\Eloquent\Model
。而是使用新的Jenssegers\Mongodb\Eloquent\HybridRelations
特质。这应该使事情更清楚,因为在这个包里只有一个模型类。
use Jenssegers\Mongodb\Eloquent\HybridRelations;
class User extends Eloquent {
use HybridRelations;
protected $connection = 'mysql';
}
嵌入关系现在返回一个Illuminate\Database\Eloquent\Collection
而不是一个自定义的集合类。如果您正在使用可用的一种特殊方法,请将其转换为集合。
$books = $user->books()->sortBy('title');
测试
要运行此包的测试,请运行:
docker-compose up
二、配置
在config/database.php
更改您的默认数据库连接名称:
'default' => env('DB_CONNECTION', 'mongodb'),
并添加一个新的mongodb
连接:
'mongodb' => [
'driver' => 'mongodb',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'options' => [
'database' => 'admin' // sets the authentication database required by mongo 3
]
],
您可以使用以下配置连接到多个服务器或副本集:
'mongodb' => [
'driver' => 'mongodb',
'host' => ['server1', 'server2'],
'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'options' => [
'replicaSet' => 'replicaSetName'
]
],
或者,您可以使用MongoDB
连接字符串:
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('DB_DSN'),
'database' => env('DB_DATABASE'),
],
请参阅MongoDB
官方文档了解它的URI格式:https://docs.mongodb.com/manual/reference/connection-string/
三、Eloquent
laravel-mongodb
包含一个MongoDB
启用的Eloquent
类,您可以使用它来定义相应集合的模型。
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {}
请注意,我们没有指定哪个Eloquent
集合用于User
模型。就像原来的Eloquent
一样,类的小写,复数名称将被用作集合名称,除非明确指定了另一个名称。您可以通过collection
在您的模型上定义属性来指定自定义集合(表的别名):
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {
protected $collection = 'users_collection';
}
注意:Eloquent
也会假设每个集合都有一个名为id
的主键列。你可以定义一个primaryKey
属性来覆盖这个定义。同样,您可以定义一个connection
属性来覆盖在使用模型时应该使用的数据库连接的名称。
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class MyModel extends Eloquent {
protected $connection = 'mongodb';
}
其他一切(应该)就像原来的Eloquent
模型一样工作。在http://laravel.com/docs/eloquent上阅读关于Eloquent
的更多信息
1、可选:Alias
您还可以通过将以下内容添加到config/app.php
别名数组中来为MongoDB
模型注册一个别名:
'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,
像下面这样就可以使用注册的别名,如:
class MyModel extends Moloquent {}
四、查询构造器
数据库驱动程序直接插入原始查询生成器。当使用mongodb
连接时,您将能够构建流畅的查询来执行数据库操作。为了您的方便,有一个collection
别名,table
以及一些额外的mongodb
特定的操作符/操作。
$users = DB::collection('users')->get();
$user = DB::collection('users')->where('name', 'John')->first();
如果您没有更改默认数据库连接,则需要在查询时指定它。
$user = DB::connection('mongodb')->collection('users')->get();
更多查询构造器参考:http://laravel.com/docs/queries
五、Schema
数据库驱动程序还具有(有限的)架构构建器支持。您可以轻松操作集合并设置索引:
Schema::create('users', function($collection)
{
$collection->index('name');
$collection->unique('email');
});
支持的操作是:
- 创建和删除
- collection
- hasCollection
- 索引和dropIndex(也支持复合索引)
- unique
- 背景,稀疏,到期,地理空间(特定于MongoDB)
所有其他(不支持的)操作都是作为
dummy
递方法实现的,因为MongoDB
不使用预定义的模式。在http://laravel.com/docs/schema上阅读有关schema
生成器的更多信息
1、地理空间索引
地理空间索引便于查询基于位置的文档。他们有两种形式:2d
和2dsphere
。使用模型构建器将这些添加到集合中。
添加一个2d
索引:
Schema::create('users', function($collection)
{
$collection->geospatial('name', '2d');
});
添加一个2dsphere
索引:
Schema::create('users', function($collection)
{
$collection->geospatial('name', '2dsphere');
});
六、扩展
1、验证
如果您想使用Laravel
的本地身份验证功能,请注册以下服务提供者:
'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider',
这个服务提供者会稍微修改内部的DatabaseReminderRepository
来添加基于MongoDB
的密码提醒的支持。如果你不使用密码提醒,你不必注册这个服务提供者,其他的一切都可以正常工作。
2、队列
如果您想使用MongoDB
作为您的数据库后端,请在config/queue.php
以下位置更改驱动程序:
'connections' => [
'database' => [
'driver' => 'mongodb',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
如果您想使用MongoDB
处理失败的jobs
,请在config/queue.php
中修改以下位置更改数据库:
'failed' => [
'database' => 'mongodb',
'table' => 'failed_jobs',
],
并在config/app.php
添加服务提供者:
Jenssegers\Mongodb\MongodbQueueServiceProvider::class,
3、Sentry
如果你想用Sentry
使用这个库,那么查看https://github.com/jenssegers/Laravel-MongoDB-Sentry
4、Sessions
MongoDB Sessions
驱动程序可以在单独的包中使用,请查看https://github.com/jenssegers/Laravel-MongoDB-Session
七、例子
1、基本用法
检索所有模型
$users = User::all();
通过主键检索记录
$user = User::find('517c43667db388101e00000f');
Wheres查询
$users = User::where('votes', '>', 100)->take(10)->get();
orWheres
$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get();
联合查询
$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get();
whereIn
语法
$users = User::whereIn('age', [16, 18, 20])->get();
whereNotIn
如果该字段不存在,则使用对象时将返回。whereNotNull('age')
把这些文件合并在一起。
使用whereBetween
$users = User::whereBetween('votes', [1, 100])->get();
null语法
$users = User::whereNull('updated_at')->get();
Order By
$users = User::orderBy('name', 'desc')->get();
Offset & Limit
$users = User::skip(10)->take(5)->get();
Distinct
需要一个字段来返回不同的值。
$users = User::distinct()->get(['name']);
// or
$users = User::distinct('name')->get();
Distinct
可以和where
共同使用:
$users = User::where('active', true)->distinct('name')->get();
高级Wheres语句
$users = User::where('name', '=', 'John')->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
Group By Selected columns that are not grouped will be aggregated with the $last function.
$users = Users::groupBy('title')->get(['title', 'name']);
Aggregation
Aggregations are only available for MongoDB versions greater than 2.2.
$total = Order::count();
$price = Order::max('price');
$price = Order::min('price');
$price = Order::avg('price');
$total = Order::sum('price');
Aggregations can be combined with where:
$sold = Orders::where('sold', true)->sum('price');
Aggregations can be also used on subdocuments:
$total = Order::max('suborder.price');
...
NOTE: this aggreagtion only works with single subdocuments (like embedsOne) not subdocument arrays (like embedsMany)
Like
$user = Comment::where('body', 'like', '%spam%')->get();
Incrementing or decrementing a value of a column
Perform increments or decrements (default 1) on specified attributes:
User::where('name', 'John Doe')->increment('age');
User::where('name', 'Jaques')->decrement('weight', 50);
The number of updated objects is returned:
$count = User->increment('age');
You may also specify additional columns to update:
User::where('age', '29')->increment('age', 1, ['group' => 'thirty something']);
User::where('bmi', 30)->decrement('bmi', 1, ['category' => 'overweight']);
Soft deleting
When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, apply the SoftDeletingTrait to the model:
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
class User extends Eloquent {
use SoftDeletes;
protected $dates = ['deleted_at'];
}
For more information check http://laravel.com/docs/eloquent#soft-deleting
MongoDB specific operators
Exists
Matches documents that have the specified field.
User::where('age', 'exists', true)->get();
All
Matches arrays that contain all elements specified in the query.
User::where('roles', 'all', ['moderator', 'author'])->get();
Size
Selects documents if the array field is a specified size.
User::where('tags', 'size', 3)->get();
Regex
Selects documents where values match a specified regular expression.
User::where('name', 'regex', new \MongoDB\BSON\Regex("/.*doe/i"))->get();
NOTE: you can also use the Laravel regexp operations. These are a bit more flexible and will automatically convert your regular expression string to a MongoDB\BSON\Regex object.
User::where('name', 'regexp', '/.*doe/i'))->get();
And the inverse:
User::where('name', 'not regexp', '/.*doe/i'))->get();
Type
Selects documents if a field is of the specified type. For more information check: http://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type
User::where('age', 'type', 2)->get();
Mod
Performs a modulo operation on the value of a field and selects documents with a specified result.
User::where('age', 'mod', [10, 0])->get();
Near
NOTE: Specify coordinates in this order: longitude, latitude.
$users = User::where('location', 'near', [
'$geometry' => [
'type' => 'Point',
'coordinates' => [
-0.1367563,
51.5100913,
],
],
'$maxDistance' => 50,
]);
GeoWithin
$users = User::where('location', 'geoWithin', [
'$geometry' => [
'type' => 'Polygon',
'coordinates' => [[
[
-0.1450383,
51.5069158,
],
[
-0.1367563,
51.5100913,
],
[
-0.1270247,
51.5013233,
],
[
-0.1450383,
51.5069158,
],
]],
],
]);
GeoIntersects
$locations = Location::where('location', 'geoIntersects', [
'$geometry' => [
'type' => 'LineString',
'coordinates' => [
[
-0.144044,
51.515215,
],
[
-0.129545,
51.507864,
],
],
],
]);
Where
Matches documents that satisfy a JavaScript expression. For more information check http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where
Inserts, updates and deletes
Inserting, updating and deleting records works just like the original Eloquent.
Saving a new model
$user = new User;
$user->name = 'John';
$user->save();
You may also use the create method to save a new model in a single line:
User::create(['name' => 'John']);
Updating a model
To update a model, you may retrieve it, change an attribute, and use the save method.
$user = User::first();
$user->email = 'john@foo.com';
$user->save();
There is also support for upsert operations, check https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operations
Deleting a model
To delete a model, simply call the delete method on the instance:
$user = User::first();
$user->delete();
Or deleting a model by its key:
User::destroy('517c43667db388101e00000f');
For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete
Dates
Eloquent allows you to work with Carbon/DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. If you wish to use this functionality on non-default date fields you will need to manually specify them as described here: http://laravel.com/docs/eloquent#date-mutators
Example:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {
protected $dates = ['birthday'];
}
Which allows you to execute queries like:
$users = User::where('birthday', '>', new DateTime('-18 years'))->get();
Relations
Supported relations are:
- hasOne
- hasMany
- belongsTo
- belongsToMany
- embedsOne
- embedsMany
Example:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {
public function items()
{
return $this->hasMany('Item');
}
}
And the inverse relation:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Item extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
The belongsToMany relation will not use a pivot "table", but will push id's to a related_ids attribute instead. This makes the second parameter for the belongsToMany method useless. If you want to define custom keys for your relation, set it to null:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {
public function groups()
{
return $this->belongsToMany('Group', null, 'user_ids', 'group_ids');
}
}
Other relations are not yet supported, but may be added in the future. Read more about these relations on http://laravel.com/docs/eloquent#relationships
EmbedsMany Relations
If you want to embed models, rather than referencing them, you can use the embedsMany relation. This relation is similar to the hasMany relation, but embeds the models inside the parent object.
REMEMBER: these relations return Eloquent collections, they don't return query builder objects!
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {
public function books()
{
return $this->embedsMany('Book');
}
}
You access the embedded models through the dynamic property:
$books = User::first()->books;
The inverse relation is automagically available, you don't need to define this reverse relation.
$user = $book->user;
Inserting and updating embedded models works similar to the hasMany relation:
$book = new Book(['title' => 'A Game of Thrones']);
$user = User::first();
$book = $user->books()->save($book);
// or
$book = $user->books()->create(['title' => 'A Game of Thrones'])
You can update embedded models using their save method (available since release 2.0.0):
$book = $user->books()->first();
$book->title = 'A Game of Thrones';
$book->save();
You can remove an embedded model by using the destroy method on the relation, or the delete method on the model (available since release 2.0.0):
$book = $user->books()->first();
$book->delete();
// or
$user->books()->destroy($book);
If you want to add or remove an embedded model, without touching the database, you can use the associate and dissociate methods. To eventually write the changes to the database, save the parent object:
$user->books()->associate($book);
$user->save();
Like other relations, embedsMany assumes the local key of the relationship based on the model name. You can override the default local key by passing a second argument to the embedsMany method:
return $this->embedsMany('Book', 'local_key');
Embedded relations will return a Collection of embedded items instead of a query builder. Check out the available operations here: https://laravel.com/docs/master/collections
EmbedsOne Relations
The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model.
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Book extends Eloquent {
public function author()
{
return $this->embedsOne('Author');
}
}
You access the embedded models through the dynamic property:
$author = Book::first()->author;
Inserting and updating embedded models works similar to the hasOne relation:
$author = new Author(['name' => 'John Doe']);
$book = Books::first();
$author = $book->author()->save($author);
// or
$author = $book->author()->create(['name' => 'John Doe']);
You can update the embedded model using the save method (available since release 2.0.0):
$author = $book->author;
$author->name = 'Jane Doe';
$author->save();
You can replace the embedded model with a new model like this:
$newAuthor = new Author(['name' => 'Jane Doe']);
$book->author()->save($newAuthor);
MySQL Relations
If you're using a hybrid MongoDB and SQL setup, you're in luck! The model will automatically return a MongoDB- or SQL-relation based on the type of the related model. Of course, if you want this functionality to work both ways, your SQL-models will need use the Jenssegers\Mongodb\Eloquent\HybridRelations trait. Note that this functionality only works for hasOne, hasMany and belongsTo relations.
Example SQL-based User model:
use Jenssegers\Mongodb\Eloquent\HybridRelations;
class User extends Eloquent {
use HybridRelations;
protected $connection = 'mysql';
public function messages()
{
return $this->hasMany('Message');
}
}
And the Mongodb-based Message model:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Message extends Eloquent {
protected $connection = 'mongodb';
public function user()
{
return $this->belongsTo('User');
}
}
Raw Expressions
These expressions will be injected directly into the query.
User::whereRaw(['age' => array('$gt' => 30, '$lt' => 40)])->get();
You can also perform raw expressions on the internal MongoCollection object. If this is executed on the model class, it will return a collection of models. If this is executed on the query builder, it will return the original response.
// Returns a collection of User models.
$models = User::raw(function($collection)
{
return $collection->find();
});
// Returns the original MongoCursor.
$cursor = DB::collection('users')->raw(function($collection)
{
return $collection->find();
});
Optional: if you don't pass a closure to the raw method, the internal MongoCollection object will be accessible:
$model = User::raw()->findOne(['age' => array('$lt' => 18)]);
The internal MongoClient and MongoDB objects can be accessed like this:
$client = DB::getMongoClient();
$db = DB::getMongoDB();
MongoDB specific operations
Cursor timeout
To prevent MongoCursorTimeout exceptions, you can manually set a timeout value that will be applied to the cursor:
DB::collection('users')->timeout(-1)->get();
Upsert
Update or insert a document. Additional options for the update method are passed directly to the native update method.
DB::collection('users')->where('name', 'John')
->update($data, ['upsert' => true]);
Projections
You can apply projections to your queries using the project method.
DB::collection('items')->project(['tags' => ['$slice' => 1]])->get();
DB::collection('items')->project(['tags' => ['$slice' => [3, 7]]])->get();
Projections with Pagination
$limit = 25;
$projections = ['id', 'name'];
DB::collection('items')->paginate($limit, $projections);
Push
Add an items to an array.
DB::collection('users')->where('name', 'John')->push('items', 'boots');
DB::collection('users')->where('name', 'John')->push('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);
If you don't want duplicate items, set the third parameter to true:
DB::collection('users')->where('name', 'John')->push('items', 'boots', true);
Pull
Remove an item from an array.
DB::collection('users')->where('name', 'John')->pull('items', 'boots');
DB::collection('users')->where('name', 'John')->pull('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);
Unset
Remove one or more fields from a document.
DB::collection('users')->where('name', 'John')->unset('note');
You can also perform an unset on a model.
$user = User::where('name', 'John')->first();
$user->unset('note');
Query Caching
You may easily cache the results of a query using the remember method:
$users = User::remember(10)->get();
From: http://laravel.com/docs/queries#caching-queries
Query Logging
By default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the disableQueryLog method:
DB::connection()->disableQueryLog();
-
laravel中distinct()的使用方法与去重 2017-09-11
-
Laravel将view缓存为静态html,laravel页面静态缓存 2021-10-09
-
[ laravel爬虫实战--基础篇 ] guzzle描述与安装 2017-11-01
-
[ 配置教程 ] 在ubuntu16.04中部署LNMP环境(php7+maridb且开启maridb远程以及nginx多域名访问 )并配置laravel环境 2017-07-18
-
laravel11如何启用routes/api.php无状态路由 2025-03-06
热门文章
-
laravel11如何启用routes/api.php无状态路由 2025-03-06
-
oppo手机默认浏览器urlscheme 2025-02-13
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
-
Mac 安装mysql并且配置密码 2024-11-20
-
阿里云不同账号(跨账号)ECS服务器同地域如何实现免费内网互通? 2024-11-12
更多相关好文