From caaf2c222db3f69aadc8152194376eefc9492019 Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Mon, 20 Jan 2020 20:30:58 +0200 Subject: [PATCH 01/14] Wip --- README.md | 1014 ++++------------------------------------------------- 1 file changed, 73 insertions(+), 941 deletions(-) diff --git a/README.md b/README.md index bfdc02c35..e6197c34f 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Laravel MongoDB [![Latest Stable Version](http://img.shields.io/github/release/jenssegers/laravel-mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Total Downloads](http://img.shields.io/packagist/dm/jenssegers/mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Build Status](https://img.shields.io/github/workflow/status/jenssegers/laravel-mongodb/CI)](https://github.com/jenssegers/laravel-mongodb/actions) [![Coverage Status](https://coveralls.io/repos/github/jenssegers/laravel-mongodb/badge.svg?branch=master)](https://coveralls.io/github/jenssegers/laravel-mongodb?branch=master) [![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/jenssegers) -An Eloquent model and Query builder with support for MongoDB, using the original Laravel API. *This library extends the original Laravel classes, so it uses exactly the same methods.* +Laravel Eloquent add support for ODM (Object Document Mapper) to Laravel. It's the same as Eloquent ORM, but with Documents, since MongoDB is a NoSQL database. Table of contents ----------------- @@ -11,25 +11,12 @@ Table of contents * [Upgrading](#upgrading) * [Configuration](#configuration) * [Eloquent](#eloquent) -* [Optional: Alias](#optional-alias) * [Query Builder](#query-builder) -* [Schema](#schema) -* [Extensions](#extensions) -* [Examples](#examples) -Installation +Laravel Installation ------------ - Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php -**WARNING**: The old mongo PHP driver is not supported anymore in versions >= 3.0. - -Installation using composer: - -``` -composer require jenssegers/mongodb -``` - ### Laravel version Compatibility Laravel | Package @@ -46,12 +33,22 @@ composer require jenssegers/mongodb 5.8.x | 3.5.x 6.0.x | 3.6.x -And add the service provider in `config/app.php`: +Install the package via Composer: + +```bash +$ composer require jenssegers/mongodb +``` + +### Laravel + +In case your Laravel version does NOT autoload the packages, add the service provider to `config/app.php`: ```php Jenssegers\Mongodb\MongodbServiceProvider::class, ``` +### Lumen + For usage with [Lumen](http://lumen.laravel.com), add the service provider in `bootstrap/app.php`. In this file, you will also need to enable Eloquent. You must however ensure that your call to `$app->withEloquent();` is **below** where you have registered the `MongodbServiceProvider`: ```php @@ -60,13 +57,16 @@ $app->register(Jenssegers\Mongodb\MongodbServiceProvider::class); $app->withEloquent(); ``` -The service provider will register a mongodb database extension with the original database manager. There is no need to register additional facades or objects. When using mongodb connections, Laravel will automatically provide you with the corresponding mongodb objects. +The service provider will register a MongoDB database extension with the original database manager. There is no need to register additional facades or objects. + +When using MongoDB connections, Laravel will automatically provide you with the corresponding MongoDB objects. + +### Non-Laravel projects For usage outside Laravel, check out the [Capsule manager](https://github.com/illuminate/database/blob/master/README.md) and add: ```php -$capsule->getDatabaseManager()->extend('mongodb', function($config, $name) -{ +$capsule->getDatabaseManager()->extend('mongodb', function($config, $name) { $config['name'] = $name; return new Jenssegers\Mongodb\Connection($config); @@ -78,34 +78,39 @@ Upgrading #### Upgrading from version 2 to 3 -In this new major release which supports the new mongodb PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait. +In this new major release which supports the new MongoDB PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait. Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files, or your registered alias. ```php use Jenssegers\Mongodb\Eloquent\Model as Eloquent; -class User extends Eloquent {} +class User extends Eloquent +{ + // +} ``` -If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class `Illuminate\Database\Eloquent\Model` instead of the removed `Jenssegers\Eloquent\Model`. Instead use the new `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. This should make things more clear as there is only one single model class in this package. +If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class `Illuminate\Database\Eloquent\Model` instead of the removed `Jenssegers\Eloquent\Model`. + +Instead use the new `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. This should make things more clear as there is only one single model class in this package. ```php use Jenssegers\Mongodb\Eloquent\HybridRelations; -class User extends Eloquent { +class User extends Eloquent +{ use HybridRelations; protected $connection = 'mysql'; - } ``` Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations. ```php -$books = $user->books()->sortBy('title'); +$books = $user->books()->sortBy('title')->get(); ``` Testing @@ -119,970 +124,97 @@ docker-compose up Configuration ------------- - -Change your default database connection name in `config/database.php`: - -```php -'default' => env('DB_CONNECTION', 'mongodb'), -``` - -And add a new mongodb connection: +You can use MongoDB either as a main database, either as a side database. To do so, add a new `mongodb` connection to `config/database.php`: ```php '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 - ] + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', 27017), + 'database' => env('DB_DATABASE', 'homestead'), + 'username' => env('DB_USERNAME', 'homestead'), + 'password' => env('DB_PASSWORD', 'secret'), + 'options' => [ + 'database' => 'admin', // required with Mongo 3+ + + // here you can pass more settings + // see https://www.php.net/manual/en/mongoclient.construct.php under "Parameters" for a list of complete parameters you can use + ], ], ``` -You can connect to multiple servers or replica sets with the following configuration: +For multiple servers or replica set configurations, set the host to array and specify each server host: ```php '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' - ] + 'host' => ['server1', 'server2', ...], + ... + 'options' => [ + 'replicaSet' => 'rs0', + ], ], ``` -Alternatively, you can use MongoDB connection string: +If you wish to use a connection string instead of a full key-value params, you can set it so. Check the documentation on MongoDB's URI format: https://docs.mongodb.com/manual/reference/connection-string/ ```php 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => env('DB_DSN'), - 'database' => env('DB_DATABASE'), + 'database' => env('DB_DATABASE', 'homestead'), ], ``` -Please refer to MongoDB official docs for its URI format: https://docs.mongodb.com/manual/reference/connection-string/ - Eloquent -------- +### Basic Usage This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections. ```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent {} -``` - -Note that we did not tell Eloquent which collection to use for the `User` model. Just like the original Eloquent, the lower-case, plural name of the class will be used as the collection name unless another name is explicitly specified. You may specify a custom collection (alias for table) by defining a `collection` property on your model: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - protected $collection = 'users_collection'; - -} -``` - -**NOTE:** Eloquent will also assume that each collection has a primary key column named id. You may define a `primaryKey` property to override this convention. Likewise, you may define a `connection` property to override the name of the database connection that should be used when utilizing the model. - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class MyModel extends Eloquent { - - protected $connection = 'mongodb'; +use Jenssegers\Mongodb\Eloquent\Model; +class Book extends Model +{ + // } ``` -Everything else (should) work just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent - -### Optional: Alias - -You may also register an alias for the MongoDB model by adding the following to the alias array in `config/app.php`: - -```php -'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class, -``` - -This will allow you to use the registered alias like: - -```php -class MyModel extends Moloquent {} -``` - -Query Builder -------------- - -The database driver plugs right into the original query builder. When using mongodb connections, you will be able to build fluent queries to perform database operations. For your convenience, there is a `collection` alias for `table` as well as some additional mongodb specific operators/operations. - -```php -$users = DB::collection('users')->get(); - -$user = DB::collection('users')->where('name', 'John')->first(); -``` - -If you did not change your default database connection, you will need to specify it when querying. - -```php -$user = DB::connection('mongodb')->collection('users')->get(); -``` - -Read more about the query builder on http://laravel.com/docs/queries - -Schema ------- +Just like a normal model, the MongoDB model class will know which collection to use based on the model name. For `Book`, the collection `books` will be used. -The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes: +To change the collection, pass the `$collection` property: ```php -Schema::create('users', function($collection) -{ - $collection->index('name'); - - $collection->unique('email'); -}); -``` -You can also pass all the parameters specified in the MongoDB docs [here](https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options-for-all-index-types) in the `$options` parameter. For example: +use Jenssegers\Mongodb\Eloquent\Model; -``` -Schema::create('users', function($collection) +class Book extends Model { - $collection->index('username',null,null,[ - 'sparse' => true, - 'unique' => true, - 'background' => true - ]); -}); + protected $collection = 'my_books_collection'; +} ``` -Supported operations are: - - - create and drop - - collection - - hasCollection - - index and dropIndex (compound indexes supported as well) - - unique - - background, sparse, expire, geospatial (MongoDB specific) - -All other (unsupported) operations are implemented as dummy pass-through methods, because MongoDB does not use a predefined schema. Read more about the schema builder on https://laravel.com/docs/6.0/migrations#tables - -### Geospatial indexes -Geospatial indexes are handy for querying location-based documents. They come in two forms: `2d` and `2dsphere`. Use the schema builder to add these to a collection. - -To add a `2d` index: +**NOTE:** MongoDb documents are automatically stored with an unique ID that is stored in the `_id` property. If you wish to use your own ID, substitude the `$primaryKey` property and set it to your own primary key attribute name. ```php -Schema::create('users', function($collection) -{ - $collection->geospatial('name', '2d'); -}); -``` +use Jenssegers\Mongodb\Eloquent\Model; -To add a `2dsphere` index: - -```php -Schema::create('users', function($collection) +class Book extends Model { - $collection->geospatial('name', '2dsphere'); -}); -``` - -Extensions ----------- - -### Auth - -If you want to use Laravel's native Auth functionality, register this included service provider: - -```php -'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider', -``` - -This service provider will slightly modify the internal DatabaseReminderRepository to add support for MongoDB based password reminders. If you don't use password reminders, you don't have to register this service provider and everything else should work just fine. - -### Queues - -If you want to use MongoDB as your database backend, change the driver in `config/queue.php`: - -```php -'connections' => [ - 'database' => [ - 'driver' => 'mongodb', - 'table' => 'jobs', - 'queue' => 'default', - 'expire' => 60, - ], -] -``` - -If you want to use MongoDB to handle failed jobs, change the database in `config/queue.php`: - -```php -'failed' => [ - 'database' => 'mongodb', - 'table' => 'failed_jobs', -], -``` - -And add the service provider in `config/app.php`: - -```php -Jenssegers\Mongodb\MongodbQueueServiceProvider::class, -``` - -### Sentry - -If you want to use this library with [Sentry](https://cartalyst.com/manual/sentry), then check out https://github.com/jenssegers/Laravel-MongoDB-Sentry - -### Sessions - -The MongoDB session driver is available in a separate package, check out https://github.com/jenssegers/Laravel-MongoDB-Session - -Examples --------- - -### Basic Usage - -**Retrieving All Models** - -```php -$users = User::all(); -``` - -**Retrieving A Record By Primary Key** - -```php -$user = User::find('517c43667db388101e00000f'); -``` - -**Wheres** - -```php -$users = User::where('votes', '>', 100)->take(10)->get(); -``` - -**Or Statements** - -```php -$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get(); -``` - -**And Statements** - -```php -$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get(); -``` - -**Using Where In With An Array** - -```php -$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** - -```php -$users = User::whereBetween('votes', [1, 100])->get(); -``` - -**Where null** - -```php -$users = User::whereNull('updated_at')->get(); -``` - -**Order By** - -```php -$users = User::orderBy('name', 'desc')->get(); -``` - -**Offset & Limit** - -```php -$users = User::skip(10)->take(5)->get(); -``` - -**Distinct** - -Distinct requires a field for which to return the distinct values. - -```php -$users = User::distinct()->get(['name']); -// or -$users = User::distinct('name')->get(); -``` - -Distinct can be combined with **where**: - -```php -$users = User::where('active', true)->distinct('name')->get(); -``` - -**Advanced Wheres** - -```php -$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. - -```php -$users = Users::groupBy('title')->get(['title', 'name']); -``` - -**Aggregation** - -*Aggregations are only available for MongoDB versions greater than 2.2.* - -```php -$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**: - -```php -$sold = Orders::where('sold', true)->sum('price'); -``` - -Aggregations can be also used on subdocuments: - -```php -$total = Order::max('suborder.price'); -... -``` - -**NOTE**: this aggreagtion only works with single subdocuments (like embedsOne) not subdocument arrays (like embedsMany) - -**Like** - -```php -$user = Comment::where('body', 'like', '%spam%')->get(); -``` - -**Incrementing or decrementing a value of a column** - -Perform increments or decrements (default 1) on specified attributes: - -```php -User::where('name', 'John Doe')->increment('age'); -User::where('name', 'Jaques')->decrement('weight', 50); -``` - -The number of updated objects is returned: - -```php -$count = User::increment('age'); -``` - -You may also specify additional columns to update: - -```php -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: - -```php -use Jenssegers\Mongodb\Eloquent\SoftDeletes; - -class User extends Eloquent { - - use SoftDeletes; - - protected $dates = ['deleted_at']; - + protected $primaryKey = 'id'; } -``` - -For more information check http://laravel.com/docs/eloquent#soft-deleting - -### MongoDB specific operators - -**Exists** - -Matches documents that have the specified field. - -```php -User::where('age', 'exists', true)->get(); -``` -**All** - -Matches arrays that contain all elements specified in the query. - -```php -User::where('roles', 'all', ['moderator', 'author'])->get(); -``` - -**Size** - -Selects documents if the array field is a specified size. - -```php -User::where('tags', 'size', 3)->get(); -``` - -**Regex** - -Selects documents where values match a specified regular expression. - -```php -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. - -```php -User::where('name', 'regexp', '/.*doe/i')->get(); -``` - -And the inverse: - -```php -User::where('name', 'not regexp', '/.*doe/i')->get(); +// Mongo will also createa _id, but the 'id' property will be used for primary key actions like find(). +Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']); ``` -**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 +Likewise, you may define a `connection` property to override the name of the database connection that should be used when utilizing the model. ```php -User::where('age', 'type', 2)->get(); -``` - -**Mod** +use Jenssegers\Mongodb\Eloquent\Model; -Performs a modulo operation on the value of a field and selects documents with a specified result. - -```php -User::where('age', 'mod', [10, 0])->get(); +class Book extends Model +{ + protected $connection = 'mongodb'; +} ``` - -**Near** - -**NOTE:** Specify coordinates in this order: `longitude, latitude`. - -```php -$users = User::where('location', 'near', [ - '$geometry' => [ - 'type' => 'Point', - 'coordinates' => [ - -0.1367563, - 51.5100913, - ], - ], - '$maxDistance' => 50, -]); -``` - -**GeoWithin** - -```php -$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** - -```php -$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** - -```php -$user = new User; -$user->name = 'John'; -$user->save(); -``` - -You may also use the create method to save a new model in a single line: - -```php -User::create(['name' => 'John']); -``` - -**Updating a model** - -To update a model, you may retrieve it, change an attribute, and use the save method. - -```php -$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: - -```php -$user = User::first(); -$user->delete(); -``` - -Or deleting a model by its key: - -```php -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: https://laravel.com/docs/5.0/eloquent#date-mutators - -Example: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - protected $dates = ['birthday']; - -} -``` - -Which allows you to execute queries like: - -```php -$users = User::where('birthday', '>', new DateTime('-18 years'))->get(); -``` - -### Relations - -Supported relations are: - - - hasOne - - hasMany - - belongsTo - - belongsToMany - - embedsOne - - embedsMany - -Example: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - public function items() - { - return $this->hasMany('Item'); - } - -} -``` - -And the inverse relation: - -```php -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`: - -```php -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 https://laravel.com/docs/master/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! - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - public function books() - { - return $this->embedsMany('Book'); - } - -} -``` - -You can access the embedded models through the dynamic property: - -```php -$books = User::first()->books; -``` - -The inverse relation is auto*magically* available, you don't need to define this reverse relation. - -```php -$user = $book->user; -``` - -Inserting and updating embedded models works similar to the `hasMany` relation: - -```php -$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): - -```php -$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): - -```php -$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: - -```php -$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: - -```php -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. - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class Book extends Eloquent { - - public function author() - { - return $this->embedsOne('Author'); - } - -} -``` - -You can access the embedded models through the dynamic property: - -```php -$author = Book::first()->author; -``` - -Inserting and updating embedded models works similar to the `hasOne` relation: - -```php -$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): - -```php -$author = $book->author; - -$author->name = 'Jane Doe'; -$author->save(); -``` - -You can replace the embedded model with a new model like this: - -```php -$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: - -```php -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: - -```php -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. - -```php -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. - -```php -// 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: - -```php -$model = User::raw()->findOne(['age' => ['$lt' => 18]]); -``` - -The internal MongoClient and MongoDB objects can be accessed like this: - -```php -$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: - -```php -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. - -```php -DB::collection('users')->where('name', 'John') - ->update($data, ['upsert' => true]); -``` - -**Projections** - -You can apply projections to your queries using the `project` method. - -```php -DB::collection('items')->project(['tags' => ['$slice' => 1]])->get(); -DB::collection('items')->project(['tags' => ['$slice' => [3, 7]]])->get(); -``` - -**Projections with Pagination** - -```php -$limit = 25; -$projections = ['id', 'name']; -DB::collection('items')->paginate($limit, $projections); -``` - - -**Push** - -Add items to an array. - -```php -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`: - -```php -DB::collection('users')->where('name', 'John')->push('items', 'boots', true); -``` - -**Pull** - -Remove an item from an array. - -```php -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. - -```php -DB::collection('users')->where('name', 'John')->unset('note'); -``` - -You can also perform an unset on a model. - -```php -$user = User::where('name', 'John')->first(); -$user->unset('note'); -``` - -### Query Caching - -You may easily cache the results of a query using the remember method: - -```php -$users = User::remember(10)->get(); -``` - -*From: https://laravel.com/docs/4.2/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: - -```php -DB::connection()->disableQueryLog(); -``` - -*From: https://laravel.com/docs/4.2/database#query-logging* From 4ec3442272d1b6d37cd1211bd1de9b13c77f6bba Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Mon, 20 Jan 2020 21:35:37 +0200 Subject: [PATCH 02/14] wip --- README.md | 910 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 898 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e6197c34f..0193d50f8 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,40 @@ Laravel Eloquent add support for ODM (Object Document Mapper) to Laravel. It's t Table of contents ----------------- -* [Installation](#installation) -* [Upgrading](#upgrading) -* [Configuration](#configuration) -* [Eloquent](#eloquent) -* [Query Builder](#query-builder) +- [Laravel MongoDB](#laravel-mongodb) + - [Table of contents](#table-of-contents) + - [Laravel Installation](#laravel-installation) + - [Laravel version Compatibility](#laravel-version-compatibility) + - [Laravel](#laravel) + - [Lumen](#lumen) + - [Non-Laravel projects](#non-laravel-projects) + - [Upgrading](#upgrading) + - [Upgrading from version 2 to 3](#upgrading-from-version-2-to-3) + - [Testing](#testing) + - [Configuration](#configuration) + - [Eloquent](#eloquent) + - [Extending the base model](#extending-the-base-model) + - [Soft Deletes](#soft-deletes) + - [Dates](#dates) + - [Basic Usage](#basic-usage) + - [MongoDB-specific operators](#mongodb-specific-operators) + - [MongoDB-specific Geo operations](#mongodb-specific-geo-operations) + - [Inserts, updates and deletes](#inserts-updates-and-deletes) + - [MongoDB specific operations](#mongodb-specific-operations) + - [Relationships](#relationships) + - [belongsToMany and pivots](#belongstomany-and-pivots) + - [EmbedsMany Relationship](#embedsmany-relationship) + - [EmbedsOne Relations](#embedsone-relations) + - [Query Builder](#query-builder) + - [Available operations](#available-operations) + - [Schema](#schema) + - [Geospatial indexes](#geospatial-indexes) + - [Extending](#extending) + - [Cross-Database Relations](#cross-database-relations) + - [Authentication](#authentication) + - [Queues](#queues) + - [Sentry](#sentry) + - [Sessions](#sessions) Laravel Installation ------------ @@ -83,9 +112,9 @@ In this new major release which supports the new MongoDB PHP extension, we also Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files, or your registered alias. ```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; +use Jenssegers\Mongodb\Eloquent\Model; -class User extends Eloquent +class User extends Model { // } @@ -98,7 +127,7 @@ Instead use the new `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. This sh ```php use Jenssegers\Mongodb\Eloquent\HybridRelations; -class User extends Eloquent +class User extends Model { use HybridRelations; @@ -128,7 +157,7 @@ You can use MongoDB either as a main database, either as a side database. To do ```php 'mongodb' => [ - 'driver' => 'mongodb', + 'driver' => 'mongodb', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', 27017), 'database' => env('DB_DATABASE', 'homestead'), @@ -147,7 +176,7 @@ For multiple servers or replica set configurations, set the host to array and sp ```php 'mongodb' => [ - 'driver' => 'mongodb', + 'driver' => 'mongodb', 'host' => ['server1', 'server2', ...], ... 'options' => [ @@ -160,7 +189,7 @@ If you wish to use a connection string instead of a full key-value params, you c ```php 'mongodb' => [ - 'driver' => 'mongodb', + 'driver' => 'mongodb', 'dsn' => env('DB_DSN'), 'database' => env('DB_DATABASE', 'homestead'), ], @@ -169,7 +198,7 @@ If you wish to use a connection string instead of a full key-value params, you c Eloquent -------- -### Basic Usage +### Extending the base model This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections. ```php @@ -218,3 +247,860 @@ class Book extends Model protected $connection = 'mongodb'; } ``` + +### Soft Deletes + +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 `Jenssegers\Mongodb\Eloquent\SoftDeletes` Trait to the model: + +```php +use Jenssegers\Mongodb\Eloquent\SoftDeletes; + +class User extends Model +{ + use SoftDeletes; + + protected $dates = ['deleted_at']; +} +``` + +For more information check [Laravel Docs about Soft Deleting](http://laravel.com/docs/eloquent#soft-deleting). + +### Dates + +Eloquent allows you to work with Carbon or DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. + +```php +use Jenssegers\Mongodb\Eloquent\Model; + +class User extends Model +{ + protected $dates = ['birthday']; +} +``` + +This allows you to execute queries like this: + +```php +$users = User::where( + 'birthday', '>', + new DateTime('-18 years') +)->get(); +``` + +### Basic Usage + +**Retrieving all models** + +```php +$users = User::all(); +``` + +**Retrieving a record by primary key** + +```php +$user = User::find('517c43667db388101e00000f'); +``` + +**Where** + +```php +$users = + User::where('age', '>', 18) + ->take(10) + ->get(); +``` + +**OR Statements** + +```php +$posts = + Post::where('votes', '>', 0) + ->orWhere('is_approved', true) + ->get(); +``` + +**AND statements** + +```php +$users = + User::where('age', '>', 18) + ->where('name', '!=', 'John') + ->get(); +``` + +**whereIn** + +```php +$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. + +**whereBetween** + +```php +$posts = Post::whereBetween('votes', [1, 100])->get(); +``` + +**whereNull** + +```php +$users = User::whereNull('age')->get(); +``` + +**Advanced wheres** + +```php +$users = + User::where('name', 'John') + ->orWhere(function ($query) { + return $query + ->where('votes', '>', 100) + ->where('title', '<>', 'Admin'); + })->get(); +``` + +**orderBy** + +```php +$users = User::orderBy('age', 'desc')->get(); +``` + +**Offset & Limit (skip & take)** + +```php +$users = + User::skip(10) + ->take(5) + ->get(); +``` + +**groupBy** + +Selected columns that are not grouped will be aggregated with the `$last` function. + +```php +$users = + Users::groupBy('title') + ->get(['title', 'name']); +``` + +**Distinct** + +Distinct requires a field for which to return the distinct values. + +```php +$users = User::distinct()->get(['name']); + +// Equivalent to: +$users = User::distinct('name')->get(); +``` + +Distinct can be combined with **where**: + +```php +$users = + User::where('active', true) + ->distinct('name') + ->get(); +``` + +**Like** + +```php +$spamComments = Comment::where('body', 'like', '%spam%')->get(); +``` + +**Aggregation** + +**Aggregations are only available for MongoDB versions greater than 2.2.x** + +```php +$total = Product::count(); +$price = Product::max('price'); +$price = Product::min('price'); +$price = Product::avg('price'); +$total = Product::sum('price'); +``` + +Aggregations can be combined with **where**: + +```php +$sold = Orders::where('sold', true)->sum('price'); +``` + +Aggregations can be also used on sub-documents: + +```php +$total = Order::max('suborder.price'); +``` + +**NOTE**: This aggregation only works with single sub-documents (like `EmbedsOne`) not subdocument arrays (like `EmbedsMany`). + +**Incrementing/Decrementing the value of a column** + +Perform increments or decrements (default 1) on specified attributes: + +```php +Cat::where('name', 'Kitty')->increment('age'); + +Car::where('name', 'Toyota')->decrement('weight', 50); +``` + +The number of updated objects is returned: + +```php +$count = User::increment('age'); +``` + +You may also specify additional columns to update: + +```php +Cat::where('age', 3) + ->increment('age', 1, ['group' => 'Kitty Club']); + +Car::where('weight', 300) + ->decrement('weight', 100, ['latest_change' => 'carbon fiber']); +``` + +### MongoDB-specific operators + +**Exists** + +Matches documents that have the specified field. + +```php +User::where('age', 'exists', true)->get(); +``` + +**All** + +Matches arrays that contain all elements specified in the query. + +```php +User::where('roles', 'all', ['moderator', 'author'])->get(); +``` + +**Size** + +Selects documents if the array field is a specified size. + +```php +Post::where('tags', 'size', 3)->get(); +``` + +**Regex** + +Selects documents where values match a specified regular expression. + +```php +use MongoDB\BSON\Regex; + +User::where('name', 'regex', new 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. + +```php +User::where('name', 'regexp', '/.*doe/i')->get(); +``` + +The inverse of regexp: + +```php +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 + +```php +User::where('age', 'type', 2)->get(); +``` + +**Mod** + +Performs a modulo operation on the value of a field and selects documents with a specified result. + +```php +User::where('age', 'mod', [10, 0])->get(); +``` + +### MongoDB-specific Geo operations + +**Near** + +```php +$bars = Bar::where('location', 'near', [ + '$geometry' => [ + 'type' => 'Point', + 'coordinates' => [ + -0.1367563, // longitude + 51.5100913, // latitude + ], + ], + '$maxDistance' => 50, +])->get(); +``` + +**GeoWithin** + +```php +$bars = Bar::where('location', 'geoWithin', [ + '$geometry' => [ + 'type' => 'Polygon', + 'coordinates' => [ + [ + [-0.1450383, 51.5069158], + [-0.1367563, 51.5100913], + [-0.1270247, 51.5013233], + [-0.1450383, 51.5069158], + ], + ], + ], +])->get(); +``` + +**GeoIntersects** + +```php +$bars = Bar::where('location', 'geoIntersects', [ + '$geometry' => [ + 'type' => 'LineString', + 'coordinates' => [ + [-0.144044, 51.515215], + [-0.129545, 51.507864], + ], + ], +])->get(); +``` +### Inserts, updates and deletes + +Inserting, updating and deleting records works just like the original Eloquent. Please check [Laravel Docs' Eloquent section](https://laravel.com/docs/6.x/eloquent). + +Here, only the MongoDB-specific operations are specified. + +### MongoDB specific operations + +**Raw Expressions** + +These expressions will be injected directly into the query. + +```php +User::whereRaw([ + 'age' => ['$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. + +**Cursor timeout** + +To prevent `MongoCursorTimeout` exceptions, you can manually set a timeout value that will be applied to the cursor: + +```php +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. + +```php +// Query Builder +DB::collection('users') + ->where('name', 'John') + ->update($data, ['upsert' => true]); + +// Eloquent +$user->update($data, ['upsert' => true]); +``` + +**Projections** + +You can apply projections to your queries using the `project` method. + +```php +DB::collection('items') + ->project(['tags' => ['$slice' => 1]]) + ->get(); + +DB::collection('items') + ->project(['tags' => ['$slice' => [3, 7]]]) + ->get(); +``` + +**Projections with Pagination** + +```php +$limit = 25; +$projections = ['id', 'name']; + +DB::collection('items') + ->paginate($limit, $projections); +``` + +**Push** + +Add items to an array. + +```php +DB::collection('users') + ->where('name', 'John') + ->push('items', 'boots'); + +$user->push('items', 'boots'); +``` + +```php +DB::collection('users') + ->where('name', 'John') + ->push('messages', [ + 'from' => 'Jane Doe', + 'message' => 'Hi John', + ]); + +$user->push('messages', [ + 'from' => 'Jane Doe', + 'message' => 'Hi John', +]); +``` + +If you **DON'T** want duplicate items, set the third parameter to `true`: + +```php +DB::collection('users') + ->where('name', 'John') + ->push('items', 'boots', true); + +$user->push('items', 'boots', true); +``` + +**Pull** + +Remove an item from an array. + +```php +DB::collection('users') + ->where('name', 'John') + ->pull('items', 'boots'); + +$user->pull('items', 'boots'); +``` + +```php +DB::collection('users') + ->where('name', 'John') + ->pull('messages', [ + 'from' => 'Jane Doe', + 'message' => 'Hi John', + ]); + +$user->pull('messages', [ + 'from' => 'Jane Doe', + 'message' => 'Hi John', +]); +``` + +**Unset** + +Remove one or more fields from a document. + +```php +DB::collection('users') + ->where('name', 'John') + ->unset('note'); + +$user->unset('note'); +``` + +### Relationships + +The only available relationships are: + - hasOne + - hasMany + - belongsTo + - belongsToMany + +The MongoDB-specific relationships are: + - embedsOne + - embedsMany + +Here is a small example: + +```php +use Jenssegers\Mongodb\Eloquent\Model; + +class User extends Model +{ + public function items() + { + return $this->hasMany(Item::class); + } +} +``` + +The inverse relation of `hasMany` is `belongsTo`: + +```php +use Jenssegers\Mongodb\Eloquent\Model; + +class Item extends Model +{ + public function user() + { + return $this->belongsTo(User::class); + } +} +``` + +### belongsToMany and pivots + +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`: + +```php +use Jenssegers\Mongodb\Eloquent\Mode; + +class User extends Model +{ + public function groups() + { + return $this->belongsToMany( + Group::class, null, 'user_ids', 'group_ids' + ); + } +} +``` + +### EmbedsMany Relationship + +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! + +```php +use Jenssegers\Mongodb\Eloquent\Model; + +class User extends Model +{ + public function books() + { + return $this->embedsMany(Book::class); + } +} +``` + +You can access the embedded models through the dynamic property: + +```php +$user = User::first(); + +foreach ($user->books as $book) { + // +} +``` + +The inverse relation is auto*magically* available. You don't need to define this reverse relation. + +```php +$book = Book::first(); + +$user = $book->user; +``` + +Inserting and updating embedded models works similar to the `hasMany` relation: + +```php +$book = $user->books()->save( + new Book(['title' => 'A Game of Thrones']) +); + +// 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): + +```php +$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): + +```php +$book->delete(); + +// Similar operation +$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: + +```php +$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: + +```php +use Jenssegers\Mongodb\Eloquent\Model; + +class User extends Model +{ + public function books() + { + return $this->embedsMany(Book::class, '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. + +```php +use Jenssegers\Mongodb\Eloquent\Model; + +class Book extends Model +{ + public function author() + { + return $this->embedsOne(Author::class); + } +} +``` + +You can access the embedded models through the dynamic property: + +```php +$book = Book::first(); +$author = $book->author; +``` + +Inserting and updating embedded models works similar to the `hasOne` relation: + +```php +$author = $book->author()->save( + new Author(['name' => 'John Doe']) +); + +// Similar +$author = + $book->author() + ->create(['name' => 'John Doe']); +``` + +You can update the embedded model using the `save` method (available since release 2.0.0): + +```php +$author = $book->author; + +$author->name = 'Jane Doe'; +$author->save(); +``` + +You can replace the embedded model with a new model like this: + +```php +$newAuthor = new Author(['name' => 'Jane Doe']); + +$book->author()->save($newAuthor); +``` + +Query Builder +------------- +The database driver plugs right into the original query builder. + +When using MongoDB connections, you will be able to build fluent queries to perform database operations. + +For your convenience, there is a `collection` alias for `table` as well as some additional MongoDB specific operators/operations. + + +```php +$books = DB::collection('books')->get(); + +$hungerGames = + DB::collection('books') + ->where('name', 'Hunger Games') + ->first(); +``` + +If you are familiar with [Eloquent Queries](http://laravel.com/docs/queries), there is the same functionality. + +### Available operations +To see the available operations, check the [Eloquent](#eloquent) section. + +Schema +------ +The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes. + +```php +Schema::create('users', function ($collection) { + $collection->index('name'); + $collection->unique('email'); +}); +``` + +You can also pass all the parameters specified [in the MongoDB docs](https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options-for-all-index-types) to the `$options` parameter: + +```php +Schema::create('users', function ($collection) { + $collection->index( + 'username', + null, + null, + [ + 'sparse' => true, + 'unique' => true, + 'background' => true, + ] + ); +}); +``` + +Inherited operations: +- create and drop +- collection +- hasCollection +- index and dropIndex (compound indexes supported as well) +- unique + +MongoDB specific operations: +- background +- sparse +- expire +- geospatial + +All other (unsupported) operations are implemented as dummy pass-through methods, because MongoDB does not use a predefined schema. + +Read more about the schema builder on [Laravel Docs](https://laravel.com/docs/6.0/migrations#tables) + +### Geospatial indexes + +Geospatial indexes are handy for querying location-based documents. + +They come in two forms: `2d` and `2dsphere`. Use the schema builder to add these to a collection. + +```php +Schema::create('bars', function ($collection) { + $collection->geospatial('location', '2d'); +}); +``` + +To add a `2dsphere` index: + +```php +Schema::create('bars', function ($collection) { + $collection->geospatial('location', '2dsphere'); +}); +``` + +Extending +--------- + +### Cross-Database Relations + +If you're using a hybrid MongoDB and SQL setup, you can define relationships across them. + +The model will automatically return a MongoDB-related or SQL-related relation based on the type of the related model. + +If you want this functionality to work both ways, your SQL-models will need use the `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. + +**This functionality only works for `hasOne`, `hasMany` and `belongsTo`.** + +The MySQL model shoul use the `HybridRelations` trait: + +```php +use Jenssegers\Mongodb\Eloquent\HybridRelations; + +class User extends Model +{ + use HybridRelations; + + protected $connection = 'mysql'; + + public function messages() + { + return $this->hasMany(Message::class); + } +} +``` +Within your MongoDB model, you should define the relationship: + +```php +use Jenssegers\Mongodb\Eloquent\Model; + +class Message extends Model +{ + protected $connection = 'mongodb'; + + public function user() + { + return $this->belongsTo(User::class); + } +} +``` + +### Authentication +If you want to use Laravel's native Auth functionality, register this included service provider: + +```php +Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class, +``` + +This service provider will slightly modify the internal DatabaseReminderRepository to add support for MongoDB based password reminders. + +If you don't use password reminders, you don't have to register this service provider and everything else should work just fine. + +### Queues +If you want to use MongoDB as your database backend, change the driver in `config/queue.php`: + +```php +'connections' => [ + 'database' => [ + 'driver' => 'mongodb', + 'table' => 'jobs', + 'queue' => 'default', + 'expire' => 60, + ], +], +``` + +If you want to use MongoDB to handle failed jobs, change the database in `config/queue.php`: + +```php +'failed' => [ + 'database' => 'mongodb', + 'table' => 'failed_jobs', +], +``` + +Last, add the service provider in `config/app.php`: + +```php +Jenssegers\Mongodb\MongodbQueueServiceProvider::class, +``` + +### Sentry +If you want to use this library with [Sentry](https://cartalyst.com/manual/sentry), then check out https://github.com/jenssegers/Laravel-MongoDB-Sentry + +### Sessions +The MongoDB session driver is available in a separate package, check out https://github.com/jenssegers/Laravel-MongoDB-Session From 6e26aed6b735426cadcc41d22f95ef9c461c472c Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Mon, 20 Jan 2020 21:37:47 +0200 Subject: [PATCH 03/14] wip --- README.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0193d50f8..eda095ae7 100644 --- a/README.md +++ b/README.md @@ -27,13 +27,16 @@ Table of contents - [MongoDB-specific Geo operations](#mongodb-specific-geo-operations) - [Inserts, updates and deletes](#inserts-updates-and-deletes) - [MongoDB specific operations](#mongodb-specific-operations) - - [Relationships](#relationships) + - [Relationships](#relationships) + - [Basic Usage](#basic-usage-1) - [belongsToMany and pivots](#belongstomany-and-pivots) - [EmbedsMany Relationship](#embedsmany-relationship) - [EmbedsOne Relations](#embedsone-relations) - [Query Builder](#query-builder) + - [Basic Usage](#basic-usage-2) - [Available operations](#available-operations) - [Schema](#schema) + - [Basic Usage](#basic-usage-3) - [Geospatial indexes](#geospatial-indexes) - [Extending](#extending) - [Cross-Database Relations](#cross-database-relations) @@ -719,7 +722,10 @@ DB::collection('users') $user->unset('note'); ``` -### Relationships +Relationships +------------- + +### Basic Usage The only available relationships are: - hasOne @@ -927,6 +933,9 @@ $book->author()->save($newAuthor); Query Builder ------------- + +### Basic Usage + The database driver plugs right into the original query builder. When using MongoDB connections, you will be able to build fluent queries to perform database operations. @@ -952,6 +961,8 @@ Schema ------ The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes. +### Basic Usage + ```php Schema::create('users', function ($collection) { $collection->index('name'); From 77cec75074032382489dbe1b913dcf56fcf89fc9 Mon Sep 17 00:00:00 2001 From: rennokki Date: Mon, 20 Jan 2020 22:13:43 +0200 Subject: [PATCH 04/14] wip [skip ci] Co-Authored-By: Stas --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eda095ae7..72a7b709b 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ class Book extends Model protected $primaryKey = 'id'; } -// Mongo will also createa _id, but the 'id' property will be used for primary key actions like find(). +// Mongo will also create _id, but the 'id' property will be used for primary key actions like find(). Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']); ``` From 2b68b0021ac206998f655f2a962b648750c18970 Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Mon, 20 Jan 2020 22:14:37 +0200 Subject: [PATCH 05/14] wip --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eda095ae7..0249197d8 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ You can use MongoDB either as a main database, either as a side database. To do 'database' => 'admin', // required with Mongo 3+ // here you can pass more settings - // see https://www.php.net/manual/en/mongoclient.construct.php under "Parameters" for a list of complete parameters you can use + // see https://www.php.net/manual/en/mongodb-driver-manager.construct.php under "Uri Options" for a list of complete parameters you can use ], ], ``` From 7e91b7a00c8fd34695a14f83abcd3733c1d1bdd6 Mon Sep 17 00:00:00 2001 From: rennokki Date: Mon, 20 Jan 2020 22:19:10 +0200 Subject: [PATCH 06/14] wip --- README.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index ab7ff3f5a..cedfe9b5e 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Laravel MongoDB [![Latest Stable Version](http://img.shields.io/github/release/jenssegers/laravel-mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Total Downloads](http://img.shields.io/packagist/dm/jenssegers/mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Build Status](https://img.shields.io/github/workflow/status/jenssegers/laravel-mongodb/CI)](https://github.com/jenssegers/laravel-mongodb/actions) [![Coverage Status](https://coveralls.io/repos/github/jenssegers/laravel-mongodb/badge.svg?branch=master)](https://coveralls.io/github/jenssegers/laravel-mongodb?branch=master) [![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/jenssegers) -Laravel Eloquent add support for ODM (Object Document Mapper) to Laravel. It's the same as Eloquent ORM, but with Documents, since MongoDB is a NoSQL database. +Laravel Eloquent adds support for ODM (Object Document Mapper) to Laravel. It's the same as Eloquent ORM, but with Documents, since MongoDB is a NoSQL database. Table of contents ----------------- @@ -112,7 +112,7 @@ Upgrading In this new major release which supports the new MongoDB PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait. -Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files, or your registered alias. +Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files or your registered alias. ```php use Jenssegers\Mongodb\Eloquent\Model; @@ -156,7 +156,7 @@ docker-compose up Configuration ------------- -You can use MongoDB either as a main database, either as a side database. To do so, add a new `mongodb` connection to `config/database.php`: +You can use MongoDB either as the main database, either as a side database. To do so, add a new `mongodb` connection to `config/database.php`: ```php 'mongodb' => [ @@ -175,7 +175,7 @@ You can use MongoDB either as a main database, either as a side database. To do ], ``` -For multiple servers or replica set configurations, set the host to array and specify each server host: +For multiple servers or replica set configurations, set the host to an array and specify each server host: ```php 'mongodb' => [ @@ -188,7 +188,7 @@ For multiple servers or replica set configurations, set the host to array and sp ], ``` -If you wish to use a connection string instead of a full key-value params, you can set it so. Check the documentation on MongoDB's URI format: https://docs.mongodb.com/manual/reference/connection-string/ +If you wish to use a connection string instead of full key-value params, you can set it so. Check the documentation on MongoDB's URI format: https://docs.mongodb.com/manual/reference/connection-string/ ```php 'mongodb' => [ @@ -226,7 +226,7 @@ class Book extends Model } ``` -**NOTE:** MongoDb documents are automatically stored with an unique ID that is stored in the `_id` property. If you wish to use your own ID, substitude the `$primaryKey` property and set it to your own primary key attribute name. +**NOTE:** MongoDB documents are automatically stored with a unique ID that is stored in the `_id` property. If you wish to use your own ID, substitute the `$primaryKey` property and set it to your own primary key attribute name. ```php use Jenssegers\Mongodb\Eloquent\Model; @@ -339,7 +339,7 @@ $users = $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. +When using `whereNotIn` objects will be returned if the field is non-existent. Combine with `whereNotNull('age')` to leave out those documents. **whereBetween** @@ -538,10 +538,10 @@ User::where('age', 'mod', [10, 0])->get(); ```php $bars = Bar::where('location', 'near', [ - '$geometry' => [ + '$geometry' => [ 'type' => 'Point', - 'coordinates' => [ - -0.1367563, // longitude + 'coordinates' => [ + -0.1367563, // longitude 51.5100913, // latitude ], ], @@ -553,9 +553,9 @@ $bars = Bar::where('location', 'near', [ ```php $bars = Bar::where('location', 'geoWithin', [ - '$geometry' => [ + '$geometry' => [ 'type' => 'Polygon', - 'coordinates' => [ + 'coordinates' => [ [ [-0.1450383, 51.5069158], [-0.1367563, 51.5100913], @@ -767,7 +767,7 @@ class Item extends Model ### belongsToMany and pivots -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. +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`: @@ -787,7 +787,7 @@ class User extends Model ### EmbedsMany Relationship -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. +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! @@ -1000,7 +1000,7 @@ MongoDB specific operations: - expire - geospatial -All other (unsupported) operations are implemented as dummy pass-through methods, because MongoDB does not use a predefined schema. +All other (unsupported) operations are implemented as dummy pass-through methods because MongoDB does not use a predefined schema. Read more about the schema builder on [Laravel Docs](https://laravel.com/docs/6.0/migrations#tables) @@ -1033,11 +1033,11 @@ If you're using a hybrid MongoDB and SQL setup, you can define relationships acr The model will automatically return a MongoDB-related or SQL-related relation based on the type of the related model. -If you want this functionality to work both ways, your SQL-models will need use the `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. +If you want this functionality to work both ways, your SQL-models will need to use the `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. **This functionality only works for `hasOne`, `hasMany` and `belongsTo`.** -The MySQL model shoul use the `HybridRelations` trait: +The MySQL model should use the `HybridRelations` trait: ```php use Jenssegers\Mongodb\Eloquent\HybridRelations; From df2a4ef2affe12543e7cb66a2903f53ac1d50dc4 Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Mon, 20 Jan 2020 22:21:39 +0200 Subject: [PATCH 07/14] Removed deprecated packages docs [skip ci] --- README.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/README.md b/README.md index ab7ff3f5a..e545a3b3a 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,6 @@ Table of contents - [Cross-Database Relations](#cross-database-relations) - [Authentication](#authentication) - [Queues](#queues) - - [Sentry](#sentry) - - [Sessions](#sessions) Laravel Installation ------------ @@ -1109,9 +1107,3 @@ Last, add the service provider in `config/app.php`: ```php Jenssegers\Mongodb\MongodbQueueServiceProvider::class, ``` - -### Sentry -If you want to use this library with [Sentry](https://cartalyst.com/manual/sentry), then check out https://github.com/jenssegers/Laravel-MongoDB-Sentry - -### Sessions -The MongoDB session driver is available in a separate package, check out https://github.com/jenssegers/Laravel-MongoDB-Session From 1bc273de1069f4edb7ca1c09376e5378e163308b Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Mon, 20 Jan 2020 22:23:13 +0200 Subject: [PATCH 08/14] Removed Table of contents heading --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 6e48d3f8f..ccd774b1e 100644 --- a/README.md +++ b/README.md @@ -5,10 +5,8 @@ Laravel MongoDB Laravel Eloquent adds support for ODM (Object Document Mapper) to Laravel. It's the same as Eloquent ORM, but with Documents, since MongoDB is a NoSQL database. -Table of contents ------------------ + - [Laravel MongoDB](#laravel-mongodb) - - [Table of contents](#table-of-contents) - [Laravel Installation](#laravel-installation) - [Laravel version Compatibility](#laravel-version-compatibility) - [Laravel](#laravel) From 1460b11446d5c8540f3b5e145bb80a438e4f40ea Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Wed, 22 Jan 2020 18:23:33 +0200 Subject: [PATCH 09/14] Fixed typos. --- README.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index ccd774b1e..5f37704f1 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,10 @@ Laravel MongoDB [![Latest Stable Version](http://img.shields.io/github/release/jenssegers/laravel-mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Total Downloads](http://img.shields.io/packagist/dm/jenssegers/mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Build Status](https://img.shields.io/github/workflow/status/jenssegers/laravel-mongodb/CI)](https://github.com/jenssegers/laravel-mongodb/actions) [![Coverage Status](https://coveralls.io/repos/github/jenssegers/laravel-mongodb/badge.svg?branch=master)](https://coveralls.io/github/jenssegers/laravel-mongodb?branch=master) [![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/jenssegers) -Laravel Eloquent adds support for ODM (Object Document Mapper) to Laravel. It's the same as Eloquent ORM, but with Documents, since MongoDB is a NoSQL database. - +This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. *This library extends the original Laravel classes, so it uses exactly the same methods.* - [Laravel MongoDB](#laravel-mongodb) - - [Laravel Installation](#laravel-installation) + - [Installation](#installation) - [Laravel version Compatibility](#laravel-version-compatibility) - [Laravel](#laravel) - [Lumen](#lumen) @@ -29,7 +28,7 @@ Laravel Eloquent adds support for ODM (Object Document Mapper) to Laravel. It's - [Basic Usage](#basic-usage-1) - [belongsToMany and pivots](#belongstomany-and-pivots) - [EmbedsMany Relationship](#embedsmany-relationship) - - [EmbedsOne Relations](#embedsone-relations) + - [EmbedsOne Relationship](#embedsone-relationship) - [Query Builder](#query-builder) - [Basic Usage](#basic-usage-2) - [Available operations](#available-operations) @@ -37,11 +36,11 @@ Laravel Eloquent adds support for ODM (Object Document Mapper) to Laravel. It's - [Basic Usage](#basic-usage-3) - [Geospatial indexes](#geospatial-indexes) - [Extending](#extending) - - [Cross-Database Relations](#cross-database-relations) + - [Cross-Database Relationships](#cross-database-relationships) - [Authentication](#authentication) - [Queues](#queues) -Laravel Installation +Installation ------------ Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php @@ -874,7 +873,7 @@ class User extends Model 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 +### EmbedsOne Relationship The embedsOne relation is similar to the embedsMany relation, but only embeds a single model. @@ -1023,7 +1022,7 @@ Schema::create('bars', function ($collection) { Extending --------- -### Cross-Database Relations +### Cross-Database Relationships If you're using a hybrid MongoDB and SQL setup, you can define relationships across them. From 922680d79eda737eb04ce1757efc84081867968d Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Wed, 22 Jan 2020 18:23:44 +0200 Subject: [PATCH 10/14] Moved upgrading to the bottom. --- README.md | 84 +++++++++++++++++++++++++++---------------------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 5f37704f1..471c606cb 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,6 @@ This package adds functionalities to the Eloquent model and Query builder for Mo - [Laravel](#laravel) - [Lumen](#lumen) - [Non-Laravel projects](#non-laravel-projects) - - [Upgrading](#upgrading) - - [Upgrading from version 2 to 3](#upgrading-from-version-2-to-3) - [Testing](#testing) - [Configuration](#configuration) - [Eloquent](#eloquent) @@ -39,6 +37,8 @@ This package adds functionalities to the Eloquent model and Query builder for Mo - [Cross-Database Relationships](#cross-database-relationships) - [Authentication](#authentication) - [Queues](#queues) + - [Upgrading](#upgrading) + - [Upgrading from version 2 to 3](#upgrading-from-version-2-to-3) Installation ------------ @@ -100,46 +100,6 @@ $capsule->getDatabaseManager()->extend('mongodb', function($config, $name) { }); ``` -Upgrading ---------- - -#### Upgrading from version 2 to 3 - -In this new major release which supports the new MongoDB PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait. - -Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files or your registered alias. - -```php -use Jenssegers\Mongodb\Eloquent\Model; - -class User extends Model -{ - // -} -``` - -If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class `Illuminate\Database\Eloquent\Model` instead of the removed `Jenssegers\Eloquent\Model`. - -Instead use the new `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. This should make things more clear as there is only one single model class in this package. - -```php -use Jenssegers\Mongodb\Eloquent\HybridRelations; - -class User extends Model -{ - - use HybridRelations; - - protected $connection = 'mysql'; -} -``` - -Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations. - -```php -$books = $user->books()->sortBy('title')->get(); -``` - Testing ------- @@ -1104,3 +1064,43 @@ Last, add the service provider in `config/app.php`: ```php Jenssegers\Mongodb\MongodbQueueServiceProvider::class, ``` + +Upgrading +--------- + +#### Upgrading from version 2 to 3 + +In this new major release which supports the new MongoDB PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait. + +Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files or your registered alias. + +```php +use Jenssegers\Mongodb\Eloquent\Model; + +class User extends Model +{ + // +} +``` + +If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class `Illuminate\Database\Eloquent\Model` instead of the removed `Jenssegers\Eloquent\Model`. + +Instead use the new `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. This should make things more clear as there is only one single model class in this package. + +```php +use Jenssegers\Mongodb\Eloquent\HybridRelations; + +class User extends Model +{ + + use HybridRelations; + + protected $connection = 'mysql'; +} +``` + +Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations. + +```php +$books = $user->books()->sortBy('title')->get(); +``` From d9f9fc74ee0360c76f5b11cd4590ed9ffb0b4f32 Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Wed, 22 Jan 2020 18:28:04 +0200 Subject: [PATCH 11/14] Fixed the failed configuration (#1830) --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 471c606cb..3170272b5 100644 --- a/README.md +++ b/README.md @@ -1054,11 +1054,17 @@ If you want to use MongoDB to handle failed jobs, change the database in `config ```php 'failed' => [ - 'database' => 'mongodb', + 'driver' => env('QUEUE_FAILED_DRIVER', 'database'), + 'database' => env('DB_CONNECTION', 'mongodb'), 'table' => 'failed_jobs', ], ``` +Or simply set your own `QUEUE_FAILED_DRIVER` environment variable to `mongodb` +```env +QUEUE_FAILED_DRIVER=mongodb +``` + Last, add the service provider in `config/app.php`: ```php From 0c4f2078283c6d5d09849a967cda876bb63e2fd6 Mon Sep 17 00:00:00 2001 From: rennokki Date: Thu, 23 Jan 2020 12:29:11 +0200 Subject: [PATCH 12/14] wip --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d20959cbc..dcb282550 100644 --- a/README.md +++ b/README.md @@ -268,8 +268,8 @@ $user = User::find('517c43667db388101e00000f'); **Where** ```php -$users = - User::where('age', '>', 18) +$posts = + Post::where('author.name', 'John') ->take(10) ->get(); ``` From 3f6b85067bc2cf4ca12f122b65f5bd12cc7c3eae Mon Sep 17 00:00:00 2001 From: rennokki Date: Thu, 23 Jan 2020 12:43:18 +0200 Subject: [PATCH 13/14] wip db authentication --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index dcb282550..90e760594 100644 --- a/README.md +++ b/README.md @@ -126,10 +126,10 @@ You can use MongoDB either as the main database, either as a side database. To d 'username' => env('DB_USERNAME', 'homestead'), 'password' => env('DB_PASSWORD', 'secret'), 'options' => [ - 'database' => 'admin', // required with Mongo 3+ - - // here you can pass more settings - // see https://www.php.net/manual/en/mongodb-driver-manager.construct.php under "Uri Options" for a list of complete parameters you can use + // here you can pass more settings to the Mongo Driver Manager + // 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 + + 'authSource' => env('DB_AUTHENTICATION_DATABASE', 'admin'), // required with Mongo 3+ ], ], ``` From 11fb8ea2efa528f2c1b724a131c66d244fce00b2 Mon Sep 17 00:00:00 2001 From: Alex Renoki Date: Fri, 24 Jan 2020 15:43:55 +0200 Subject: [PATCH 14/14] Revert to 'database' --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 90e760594..b30a3404e 100644 --- a/README.md +++ b/README.md @@ -128,8 +128,8 @@ You can use MongoDB either as the main database, either as a side database. To d 'options' => [ // here you can pass more settings to the Mongo Driver Manager // 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 - - 'authSource' => env('DB_AUTHENTICATION_DATABASE', 'admin'), // required with Mongo 3+ + + 'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'), // required with Mongo 3+ ], ], ```