laravel 操作mongodb

配置

修改config/database.php在connection數組中添加mongodb的配置信息,如下

'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'
   ]
],

Eloquent

這個包包括啟動Mongodb Eloquent的類,你也可以調用響應的類使用

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class User extends Eloquent {}

聲明默認鏈接

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class MyModel extends Eloquent {
  protected $connection = 'mongodb';
}

Optional: Alias

你也可以通過添加以下在配置 app.php別名陣列登記為MongoDB模型別名:

'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,

你就可以使用別名:

class MyModel extends Moloquent {}

Query Builder

數據庫驅動程序直接插入原始查詢生成器中。當使用MongoDB的連接,你將能夠建立良好的查詢執行數據庫操作。為了您的方便,有許多別名表以及一些額外的MongoDB具體運營/操作。

$users = DB::collection('users')->get();
$user = DB::collection('users')->where('name', 'John')->first();

如果沒有更改默認數據庫連接,則需要在查詢時指定它。

$user = DB::connection('mongodb')->collection('users')->get();

Schema(數據庫結構)

你可以依照laravel Schema設置索引:

Schema::create('users', function($collection)
{
  $collection->index('name');
  $collection->unique('email');
});

示例

基本使用

查出所有user

$users = User::all();

按主鍵檢索記錄

$user = User::find('517c43667db388101e00000f');

where操作查詢

$users = User::where('votes', '>', 100)->take(10)->get();

or操作

$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get();

and操作

$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get();

Using Where In With An Array

$users = User::whereIn('age', [16, 18, 20])->get();

When using whereNotIn objects will be returned if the field is non existent. Combine with whereNotNull('age')
to leave out those documents.
Using Where Between

$users = User::whereBetween('votes', [1, 100])->get();

Where 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
Distinct requires a field for which to return the distinct values.

$users = User::distinct()->get(['name']);// or$users = User::distinct('name')->get();

Distinct can be combined with where:

$users = User::where('active', true)->distinct('name')->get();

Advanced 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
[

](https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operators)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();

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' => array('$slice' => 1]))->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();

From: http://laravel.com/docs/database#query-logging

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,546評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,570評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,505評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,017評論 1 313
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,786評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,219評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,287評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,438評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,971評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,796評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,995評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,540評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,230評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,918評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,697評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,511評論 5 6
  • 從我踏入大學的那一刻起,我似乎就被打上工程師的烙印。縱然我考上了公務員,但是我仍然無法放下那門技能。用Pyt...
    失落的地平線閱讀 429評論 0 1
  • 每個人都有每個人的性格 每個人都有跟別人相處的方式 每個都會有積極和負面的情緒 每個人都經歷一個自我認知的過程 也...
    念時光z閱讀 188評論 0 0
  • 總是對自己說要練習,但始終沒有動手。不能縱容自己偷懶了,不管畫得多難看,總有起步的那一刻。
    思來狼閱讀 351評論 1 3
  • 「原創第 134 篇」 自從接受了其他平臺的約稿,我每天的工作變得非常忙碌,常常一邊開著會,一邊微信上有好幾個客戶...
    顧小寶閱讀 357評論 6 5