From 8799f7433a19e43a3f18f11369d09fdca8f7c2a3 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 15 Mar 2024 13:42:59 -0400 Subject: [PATCH 01/36] DOCSP-35966: Query builder standardization --- docs/retrieve.txt | 190 ++++++++-------------------------------------- 1 file changed, 31 insertions(+), 159 deletions(-) diff --git a/docs/retrieve.txt b/docs/retrieve.txt index b607d3d4f..1447d20a0 100644 --- a/docs/retrieve.txt +++ b/docs/retrieve.txt @@ -43,7 +43,7 @@ sample data and creating the following files in your Laravel web application: - ``browse_movies.blade.php`` file, which contains HTML code to display the results of database operations -The following sections describe how to edit the files in your Laravel application to run +The following sections describe how to edit the files in your Laravel application to run the find operation code examples and view the expected output. .. _laravel-retrieve-matching: @@ -51,41 +51,37 @@ the find operation code examples and view the expected output. Retrieve Documents that Match a Query ------------------------------------- -You can retrieve documents that match a set of criteria by passing a query filter to the ``where()`` -method. A query filter specifies field value requirements and instructs the find operation -to only return documents that meet these requirements. To run the query, call the ``where()`` -method on an Eloquent model or query builder that represents your collection. +You can use Laravel's Eloquent object-relational mapper (ORM) to create models +that represent MongoDB collections and chain methods on them to specify +query criteria. -You can use one of the following ``where()`` method calls to build a query: - -- ``where('', )``: builds a query that matches documents in which the - target field has the exact specified value +To retrieve documents that match a set of criteria, pass a query filter to the +``where()`` method. -- ``where('', '', )``: builds a query that matches - documents in which the target field's value meets the comparison criteria +A query filter specifies field value requirements and instructs the find +operation to return only documents that meet these requirements. -After building your query with the ``where()`` method, use the ``get()`` method to -retrieve the query results. +You can use Laravel's Eloquent object-relational mapper (ORM) to create models +that represent MongoDB collections. To retrieve documents from a collection, +call the ``where()`` method on the collection's corresponding Eloquent model. -To apply multiple sets of criteria to the find operation, you can chain a series -of ``where()`` methods together. - -.. tip:: +You can use one of the following ``where()`` method calls to build a query: - To learn more about other query methods in {+odm-short+}, see the :ref:`laravel-query-builder` - page. +- ``where('', )`` builds a query that matches documents in + which the target field has the exact specified value -.. _laravel-retrieve-eloquent: +- ``where('', '', )`` builds a query + that matches documents in which the target field's value meets the comparison + criteria -Use Eloquent Models to Retrieve Documents -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +To apply multiple sets of criteria to the find operation, you can chain a series +of ``where()`` methods together. -You can use Laravel's Eloquent object-relational mapper (ORM) to create models that represent -MongoDB collections. To retrieve documents from a collection, call the ``where()`` method -on the collection's corresponding Eloquent model. +After building your query with the ``where()`` method, chain the ``get()`` +method to retrieve the query results. -This example calls two ``where()`` methods on the ``Movie`` Eloquent model to retrieve -documents that meet the following criteria: +This example calls two ``where()`` methods on the ``Movie`` Eloquent model to +retrieve documents that meet the following criteria: - ``year`` field has a value of ``2010`` - ``imdb.rating`` nested field has a value greater than ``8.5`` @@ -122,7 +118,7 @@ documents that meet the following criteria: $movies = Movie::where('year', 2010) ->where('imdb.rating', '>', 8.5) ->get(); - + return view('browse_movies', [ 'movies' => $movies ]); @@ -149,132 +145,8 @@ documents that meet the following criteria: Plot: A documentary on Brazilian Formula One racing driver Ayrton Senna, who won the F1 world championship three times before his death at age 34. -.. _laravel-retrieve-query-builder: - -Use Laravel Queries to Retrieve Documents -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can use Laravel's database query builder to run find operations instead of using Eloquent -models. To run the database query, import the ``DB`` facade into your controller file and use -Laravel's query builder syntax. - -This example uses Laravel's query builder to retrieve documents in which the value -of the ``imdb.votes`` nested field is ``350``. - -.. tabs:: - - .. tab:: Query Syntax - :tabid: query-syntax - - Use the following syntax to specify the query: - - .. code-block:: php - - $movies = DB::connection('mongodb') - ->collection('movies') - ->where('imdb.votes', 350) - ->get(); - - .. tab:: Controller Method - :tabid: controller - - To see the query results in the ``browse_movies`` view, edit the ``show()`` function - in the ``MovieController.php`` file to resemble the following code: - - .. io-code-block:: - :copyable: true - - .. input:: - :language: php - - class MovieController - { - public function show() - { - $movies = DB::connection('mongodb') - ->collection('movies') - ->where('imdb.votes', 350) - ->get(); - - return view('browse_movies', [ - 'movies' => $movies - ]); - } - } - - .. output:: - :language: none - :visible: false - - Title: Murder in New Hampshire: The Pamela Wojas Smart Story - Year: 1991 - Runtime: 100 - IMDB Rating: 5.9 - IMDB Votes: 350 - Plot: Pamela Smart knows exactly what she wants and is willing to do - anything to get it. She is fed up with teaching, and her marriage offers - little excitement. Looking for a way out she applies ... - - Title: Ah Fu - Year: 2000 - Runtime: 105 - IMDB Rating: 6.6 - IMDB Votes: 350 - Plot: After a 13-year imprisonment in Hong Kong, a kickboxer challenges the - current champion in order to restore his honor. - - Title: Bandage - Year: 2010 - Runtime: 119 - IMDB Rating: 7 - IMDB Votes: 350 - Plot: Four boys have their friendship and musical talents tested in the ever - changing worlds of the music industry and real life in 1990s Japan. - - Title: Great Migrations - Year: 2010 - Runtime: 45 - IMDB Rating: 8.2 - IMDB Votes: 350 - Plot: Great Migrations takes viewers on the epic journeys animals undertake to - ensure the survival of their species. - - Then, make the following changes to your Laravel Quick Start application: - - - Import the ``DB`` facade into your ``MovieController.php`` file by adding the - ``use Illuminate\Support\Facades\DB`` use statement - - Replace the contents of your ``browse_movies.blade.php`` file with the following code: - - .. code-block:: php - - - - - Browse Movies - - -

Movies

- - @forelse ($movies as $movie) -

- Title: {{ $movie['title'] }}
- Year: {{ $movie['year'] }}
- Runtime: {{ $movie['runtime'] }}
- IMDB Rating: {{ $movie['imdb']['rating'] }}
- IMDB Votes: {{ $movie['imdb']['votes'] }}
- Plot: {{ $movie['plot'] }}
-

- @empty -

No results

- @endforelse - - - - - .. note:: - - Since the Laravel query builder returns data as an array rather than as instances of the Eloquent model class, - the view accesses the fields by using the array syntax instead of the ``->`` object operator. +To learn how to query by using the Laravel query builder instead of the +Eloquent ORM, see the :ref:`laravel-query-builder` page. .. _laravel-retrieve-all: @@ -295,10 +167,10 @@ Use the following syntax to run a find operation that matches all documents: .. warning:: The ``movies`` collection in the Atlas sample dataset contains a large amount of data. - Retrieving and displaying all documents in this collection might cause your web - application to time out. - - To avoid this issue, specify a document limit by using the ``take()`` method. For + Retrieving and displaying all documents in this collection might cause your web + application to time out. + + To avoid this issue, specify a document limit by using the ``take()`` method. For more information about ``take()``, see the :ref:`laravel-modify-find` section of this guide. @@ -462,7 +334,7 @@ field. IMDB Votes: 620 Plot: A documentary of black art. -.. tip:: +.. tip:: To learn more about sorting, see the following resources: From 3f4192124a6faac6c06c5ea6beb49e94d8fe5ccc Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 15 Mar 2024 16:40:41 -0400 Subject: [PATCH 02/36] WIP --- docs/query-builder.txt | 650 ++++++++--------------------------------- 1 file changed, 119 insertions(+), 531 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 18f03a2e1..a243dc7f0 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -9,588 +9,176 @@ Query Builder :values: tutorial .. meta:: - :keywords: php framework, odm, code example + :keywords: code example -The database driver plugs right into the original query builder. +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol -When using MongoDB connections, you will be able to build fluent queries to -perform database operations. +Overview +-------- -For your convenience, there is a ``collection`` alias for ``table`` and -other MongoDB specific operators/operations. - -.. code-block:: php - - $books = DB::collection('books')->get(); - - $hungerGames = - DB::collection('books') - ->where('name', 'Hunger Games') - ->first(); - -If you are familiar with `Eloquent Queries `__, -there is the same functionality. - -Available operations --------------------- - -**Retrieving all models** - -.. code-block:: php - - $users = User::all(); - -**Retrieving a record by primary key** - -.. code-block:: php - - $user = User::find('517c43667db388101e00000f'); - -**Where** - -.. code-block:: php - - $posts = - Post::where('author.name', 'John') - ->take(10) - ->get(); - -**OR Statements** - -.. code-block:: php - - $posts = - Post::where('votes', '>', 0) - ->orWhere('is_approved', true) - ->get(); - -**AND statements** - -.. code-block:: php - - $users = - User::where('age', '>', 18) - ->where('name', '!=', 'John') - ->get(); - -**NOT statements** - -.. code-block:: php - - $users = User::whereNot('age', '>', 18)->get(); - -**whereIn** - -.. code-block:: 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 omit those documents. - -**whereBetween** - -.. code-block:: php - - $posts = Post::whereBetween('votes', [1, 100])->get(); - -**whereNull** - -.. code-block:: php - - $users = User::whereNull('age')->get(); - -**whereDate** - -.. code-block:: php - - $users = User::whereDate('birthday', '2021-5-12')->get(); - -The usage is the same as ``whereMonth`` / ``whereDay`` / ``whereYear`` / ``whereTime`` - -**Advanced wheres** - -.. code-block:: php - - $users = - User::where('name', 'John') - ->orWhere(function ($query) { - return $query - ->where('votes', '>', 100) - ->where('title', '<>', 'Admin'); - })->get(); - -**orderBy** - -.. code-block:: php - - $users = User::orderBy('age', 'desc')->get(); - -**Offset & Limit (skip & take)** - -.. code-block:: php - - $users = - User::skip(10) - ->take(5) - ->get(); - -**groupBy** - -Selected columns that are not grouped will be aggregated with the ``$last`` -function. - -.. code-block:: php - - $users = - Users::groupBy('title') - ->get(['title', 'name']); - -**Distinct** - -Distinct requires a field for which to return the distinct values. - -.. code-block:: php - - $users = User::distinct()->get(['name']); - - // Equivalent to: - $users = User::distinct('name')->get(); - -Distinct can be combined with **where**: - -.. code-block:: php - - $users = - User::where('active', true) - ->distinct('name') - ->get(); - -**Like** - -.. code-block:: php - - $spamComments = Comment::where('body', 'like', '%spam%')->get(); - -**Aggregation** - -**Aggregations are only available for MongoDB versions greater than 2.2.x** - -.. code-block:: 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**: - -.. code-block:: php - - $sold = Orders::where('sold', true)->sum('price'); - -Aggregations can be also used on sub-documents: - -.. code-block:: php - - $total = Order::max('suborder.price'); +In this guide, you can learn how to use the {+odm-short+} extension of +the Laravel query builder to work with a MongoDB database. The query builder +lets you write queries for any supported database by using the same fluent +interface and syntax. .. 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: - -.. code-block:: php - - Cat::where('name', 'Kitty')->increment('age'); - - Car::where('name', 'Toyota')->decrement('weight', 50); + {+odm-short+} extends Laravel's query builder and Eloquent ORM, both of + which can run similar database operations. To learn more about retrieving + documents by using Eloquent models, see :ref:`laravel-fundamentals-retrieve`. -The number of updated objects is returned: +Laravel provides a **facade** to access the query builder class ``DB``, which +lets you perform database operations. Facades are static interfaces to +classes that make the syntax more concise, avoid runtime errors,and improve +testability. -.. code-block:: php - - $count = User::increment('age'); - -You may also specify more columns to update: +{+odm-short+} aliases the ``DB`` method ``table()`` as ``collection()``. Chain +methods to specify the command and any constraints. Then, chain the ``get()`` +method at the end to run them on the MongoDB collection. The following example +shows the structure of a query builder call: .. code-block:: php - Cat::where('age', 3) - ->increment('age', 1, ['group' => 'Kitty Club']); - - Car::where('weight', 300) - ->decrement('weight', 100, ['latest_change' => 'carbon fiber']); + DB::collection('') + // chain methods by using the -> operator + ->get(); -MongoDB-specific operators -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In addition to the Laravel Eloquent operators, all available MongoDB query -operators can be used with ``where``: - -.. code-block:: php - User::where($fieldName, $operator, $value)->get(); +This guide shows how to perform the following query builder operations: -It generates the following MongoDB filter: +- Retrieve Documents + - Where Method + - Logical Conditionals (orWhere, whereNot, and And) +- Range and types (whereBetween, whereNull, whereDate) +- Array operations (whereIn, +- Nesting Logic Groups +- Modify results: orderBy, groupBy, skip, projection, projection with pagination +- Distinct +- Like +- Aggregations (is this in Query Builder?) +- MongoDB query operators +- MongoDB Raw Expressions +- MongoDB Cursor Timeout -.. code-block:: ts - { $fieldName: { $operator: $value } } +- Increment/ decrement (are these write?) -**Exists** +MongoDB Write Operations -Matches documents that have the specified field. +- Upsert +- Combine with Paginate (is this necessary?) +- Modify arrays - push and pull +- Remove a field from a document - unset -.. code-block:: php - - User::where('age', 'exists', true)->get(); - -**All** - -Matches arrays that contain all elements specified in the query. - -.. code-block:: php - User::where('roles', 'all', ['moderator', 'author'])->get(); +Before You Get Started +---------------------- -**Size** - -Selects documents if the array field is a specified size. - -.. code-block:: php - - Post::where('tags', 'size', 3)->get(); - -**Regex** - -Selects documents where values match a specified regular expression. - -.. code-block:: php - - use MongoDB\BSON\Regex; - - User::where('name', 'regex', new Regex('.*doe', 'i'))->get(); +To run the code examples in this guide, complete the +:ref:`Quick Start ` tutorial and paste the example code +in the appropriate controller method. .. note:: - You can also use the Laravel regexp operations. These will automatically - convert your regular expression string to a ``MongoDB\BSON\Regex`` object. - -.. code-block:: php - - User::where('name', 'regexp', '/.*doe/i')->get(); - -The inverse of regexp: - -.. code-block:: php - - User::where('name', 'not regexp', '/.*doe/i')->get(); - -**ElemMatch** - -The :manual:`$elemMatch ` operator -matches documents that contain an array field with at least one element that -matches all the specified query criteria. - -The following query matches only those documents where the results array -contains at least one element that is both greater than or equal to 80 and -is less than 85: - -.. code-block:: php - - User::where('results', 'elemMatch', ['gte' => 80, 'lt' => 85])->get(); - -A closure can be used to create more complex sub-queries. - -The following query matches only those documents where the results array -contains at least one element with both product equal to "xyz" and score -greater than or equal to 8: - -.. code-block:: php - - User::where('results', 'elemMatch', function (Builder $builder) { - $builder - ->where('product', 'xyz') - ->andWhere('score', '>', 50); - })->get(); - -**Type** - -Selects documents if a field is of the specified type. For more information -check: :manual:`$type ` in the -MongoDB Server documentation. - -.. code-block:: 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. - -.. code-block:: php + The view in the Quick Start tutorial displays object results. However, the + Laravel query builder returns array results. Modify the view to use array + access syntax instead of object access syntax as shown in the following + example:. - User::where('age', 'mod', [10, 0])->get(); + .. code-block:: php -MongoDB-specific Geo operations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Object access syntax + {{ $movie->imdb->votes }} -**Near** + // Array access syntax + {{ $movie['imdb']['votes'] }} -.. code-block:: php +.. _laravel-retrieve-query-builder: - $bars = Bar::where('location', 'near', [ - '$geometry' => [ - 'type' => 'Point', - 'coordinates' => [ - -0.1367563, // longitude - 51.5100913, // latitude - ], - ], - '$maxDistance' => 50, - ])->get(); +Retrieve Documents +------------------ -**GeoWithin** +To retrieve documents by using the query builder, import the +``Illuminate\Support\Facades\DB`` facade and compose your query by using +Laravel's query builder syntax. -.. code-block:: 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** +Where Method Example +~~~~~~~~~~~~~~~~~~~~ -.. code-block:: php +The following example shows how to use the ``where()`` method retrieve +documents from the ``movies`` collection that contain a ``imdb.votes`` field +value of ``350``. Click the :guilabel:`{+code-output-label+}` button to see the +results returned from the query: - $bars = Bar::where('location', 'geoIntersects', [ - '$geometry' => [ - 'type' => 'LineString', - 'coordinates' => [ - [-0.144044, 51.515215], - [-0.129545, 51.507864], - ], - ], - ])->get(); - -**GeoNear** - -You can make a ``geoNear`` query on MongoDB. -You can omit specifying the automatic fields on the model. -The returned instance is a collection, so you can call the `Collection `__ operations. -Make sure that your model has a ``location`` field, and a -`2ndSphereIndex `__. -The data in the ``location`` field must be saved as `GeoJSON `__. -The ``location`` points must be saved as `WGS84 `__ -reference system for geometry calculation. That means that you must -save ``longitude and latitude``, in that order specifically, and to find near -with calculated distance, you ``must do the same way``. - -.. code-block:: - - Bar::find("63a0cd574d08564f330ceae2")->update( - [ - 'location' => [ - 'type' => 'Point', - 'coordinates' => [ - -0.1367563, - 51.5100913 - ] - ] - ] - ); - $bars = Bar::raw(function ($collection) { - return $collection->aggregate([ - [ - '$geoNear' => [ - "near" => [ "type" => "Point", "coordinates" => [-0.132239, 51.511874] ], - "distanceField" => "dist.calculated", - "minDistance" => 0, - "maxDistance" => 6000, - "includeLocs" => "dist.location", - "spherical" => true, - ] - ] - ]); - }); - -Inserts, updates and deletes -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Inserting, updating and deleting records works just like the original Eloquent. -Please check `Laravel Docs' Eloquent section `__. - -Here, only the MongoDB-specific operations are specified. - -MongoDB specific operations -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -**Raw Expressions** - -These expressions will be injected directly into the query. +.. io-code-block:: -.. code-block:: php + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query where + :end-before: end query where - User::whereRaw([ - 'age' => ['$gt' => 30, '$lt' => 40], - ])->get(); + .. output:: + :language: none + :visible: false - User::whereRaw([ - '$where' => '/.*123.*/.test(this.field)', - ])->get(); + Title: Cosmos + Year: 1980 + Runtime: 60 + IMDB Rating: 9.3 + IMDB Votes: 17174 + Plot: Astronomer Carl Sagan leads us on an engaging guided tour of the various elements and cosmological theories of the universe. - User::whereRaw([ - '$where' => '/.*123.*/.test(this["hyphenated-field"])', - ])->get(); + Title: The Shawshank Redemption + Year: 1994 + Runtime: 142 + IMDB Rating: 9.3 + IMDB Votes: 1521105 + Plot: Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency. -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. + Title: The Shawshank Redemption + Year: 1994 + Runtime: 142 + IMDB Rating: 9.3 + IMDB Votes: 1513145 + Plot: Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency. -If this is executed on the query builder, it will return the original response. + Title: The Real Miyagi + Year: 2015 + Runtime: 90 + IMDB Rating: 9.3 + IMDB Votes: 41 + Plot: The life of the greatest karate master of a generation. -**Cursor timeout** +Logical Conditional Operation Examples +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To prevent ``MongoCursorTimeout`` exceptions, you can manually set a timeout -value that will be applied to the cursor: +The examples in this section show query builder syntax you can use to perform +the following logical conditional operations: -.. code-block:: php +- **OR** by chaining the ``orWhere()`` function +- **AND** by chaining another ``where()`` function +- **NOT** which uses the ``whereNot()`` function - DB::collection('users')->timeout(-1)->get(); -**Upsert** -Update or insert a document. Other options for the update method can be -passed directly to the native update method. -.. code-block:: 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. - -.. code-block:: php +The following example shows how to use the following logical conditional +operations: - DB::collection('items') - ->project(['tags' => ['$slice' => 1]]) - ->get(); - DB::collection('items') - ->project(['tags' => ['$slice' => [3, 7]]]) - ->get(); +``where()`` method retrieve +documents from the ``movies`` collection that contain a ``imdb.votes`` field +value of ``350``. Click the :guilabel:`{+code-output-label+}` button to see the +results returned from the query: -**Projections with Pagination** - -.. code-block:: php - - $limit = 25; - $projections = ['id', 'name']; - - DB::collection('items') - ->paginate($limit, $projections); - -**Push** - -Add items to an array. - -.. code-block:: php - - DB::collection('users') - ->where('name', 'John') - ->push('items', 'boots'); - - $user->push('items', 'boots'); - -.. code-block:: php +s (orWhere, whereNot, and And) - 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``: - -.. code-block:: php - - DB::collection('users') - ->where('name', 'John') - ->push('items', 'boots', true); - - $user->push('items', 'boots', true); - -**Pull** - -Remove an item from an array. - -.. code-block:: php - - DB::collection('users') - ->where('name', 'John') - ->pull('items', 'boots'); - - $user->pull('items', 'boots'); - -.. code-block:: 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. - -.. code-block:: php - - DB::collection('users') - ->where('name', 'John') - ->unset('note'); - - $user->unset('note'); - - $user->save(); - -Using the native ``unset`` on models will work as well: - -.. code-block:: php - unset($user['note']); - unset($user->node); From c90150ab83c9061e61624de0af378d8e7ec6280d Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Mon, 18 Mar 2024 14:34:48 -0400 Subject: [PATCH 03/36] wip --- docs/query-builder.txt | 106 ++++++++++++++++++++++++++--------------- 1 file changed, 68 insertions(+), 38 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index a243dc7f0..43df8a7f5 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -39,63 +39,59 @@ testability. {+odm-short+} aliases the ``DB`` method ``table()`` as ``collection()``. Chain methods to specify the command and any constraints. Then, chain the ``get()`` method at the end to run them on the MongoDB collection. The following example -shows the structure of a query builder call: +shows the syntax of a query builder call: .. code-block:: php DB::collection('') - // chain methods by using the -> operator - ->get(); - - -This guide shows how to perform the following query builder operations: - -- Retrieve Documents - - Where Method - - Logical Conditionals (orWhere, whereNot, and And) -- Range and types (whereBetween, whereNull, whereDate) -- Array operations (whereIn, -- Nesting Logic Groups + // chain methods by using the "->" object operator + ->get(); + +This guide shows examples of the following query builder operations: + +- Retrieve documents + - Logical conditionals (orWhere, whereNot, and And) + - Nested logic groups + - Range (whereBetween, whereDate) + - Check for ``null`` values (whereNull) + - Array operations (whereIn, ...) + - Pattern search (like) +- Retrieve distinct values - Modify results: orderBy, groupBy, skip, projection, projection with pagination -- Distinct -- Like -- Aggregations (is this in Query Builder?) - MongoDB query operators -- MongoDB Raw Expressions -- MongoDB Cursor Timeout - + - General + - Array + - Geospatial + - Projection + - MongoDB cursor timeout + - MongoDB raw expressions +- Aggregations (is this in Query Builder?) -- Increment/ decrement (are these write?) +- Write operations +- MongoDB write operations + - Upsert + - Increment/ decrement + - Modify array values - push, pull + - Remove a field from a document - Unset MongoDB Write Operations -- Upsert - Combine with Paginate (is this necessary?) - Modify arrays - push and pull -- Remove a field from a document - unset - Before You Get Started ---------------------- To run the code examples in this guide, complete the :ref:`Quick Start ` tutorial and paste the example code -in the appropriate controller method. +in the ``show()`` controller method. -.. note:: +.. + TODO: this requirement can be removed after https://jira.mongodb.org/browse/DOCSP-37770 is completed - The view in the Quick Start tutorial displays object results. However, the - Laravel query builder returns array results. Modify the view to use array - access syntax instead of object access syntax as shown in the following - example:. - - .. code-block:: php - - // Object access syntax - {{ $movie->imdb->votes }} - - // Array access syntax - {{ $movie['imdb']['votes'] }} + Replace the `browse_movie.blade.php `__ + file, which accesses Eloquent ORM operation results, with the `browse_movies_array.blade.php `__ + file to access the ar .. _laravel-retrieve-query-builder: @@ -106,6 +102,9 @@ To retrieve documents by using the query builder, import the ``Illuminate\Support\Facades\DB`` facade and compose your query by using Laravel's query builder syntax. +This section includes examples on the following operators: +TODO + Where Method Example ~~~~~~~~~~~~~~~~~~~~ @@ -165,6 +164,27 @@ the following logical conditional operations: - **AND** by chaining another ``where()`` function - **NOT** which uses the ``whereNot()`` function +- Nesting logical conditionals: year 2010 + + +OR - back to the future or year 1955 +.. io-code-block:: + + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query orWhere + :end-before: end query orWhere + + .. output:: + :language: none + :visible: false + + + +AND - rating == 8.2 and duration < 30 + +NOT - type != movie @@ -177,7 +197,17 @@ documents from the ``movies`` collection that contain a ``imdb.votes`` field value of ``350``. Click the :guilabel:`{+code-output-label+}` button to see the results returned from the query: -s (orWhere, whereNot, and And) +- Range and types (whereBetween, whereNull, whereDate) + +whereBetween - rating 9 and 10 +whereNull runtime: null +whereDate released between 2002 2005 + + + +regex: +"The Lord of % ..." + From e386f25b93ecf35f195ac130cf93a5a56cd0cf11 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Tue, 19 Mar 2024 17:07:41 -0400 Subject: [PATCH 04/36] WIP --- docs/query-builder.txt | 435 +++++++++++++++++++++++++++++++++++------ 1 file changed, 377 insertions(+), 58 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 43df8a7f5..f9dc276da 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -47,37 +47,16 @@ shows the syntax of a query builder call: // chain methods by using the "->" object operator ->get(); -This guide shows examples of the following query builder operations: - -- Retrieve documents - - Logical conditionals (orWhere, whereNot, and And) - - Nested logic groups - - Range (whereBetween, whereDate) - - Check for ``null`` values (whereNull) - - Array operations (whereIn, ...) - - Pattern search (like) -- Retrieve distinct values -- Modify results: orderBy, groupBy, skip, projection, projection with pagination -- MongoDB query operators - - General - - Array - - Geospatial - - Projection - - MongoDB cursor timeout - - MongoDB raw expressions -- Aggregations (is this in Query Builder?) +This guide shows examples of the following types of query builder operations: -- Write operations -- MongoDB write operations - - Upsert - - Increment/ decrement - - Modify array values - push, pull - - Remove a field from a document - Unset +- :ref:`laravel-retrieve-query-builder` +- :ref:`laravel-modify-results-query-builder` +- :ref:`laravel-mongodb-read-query-builder` +- :ref:`laravel-mongodb-write-query-builder` -MongoDB Write Operations +- Write operations + - link to -- Combine with Paginate (is this necessary?) -- Modify arrays - push and pull Before You Get Started ---------------------- @@ -99,12 +78,20 @@ Retrieve Documents ------------------ To retrieve documents by using the query builder, import the -``Illuminate\Support\Facades\DB`` facade and compose your query by using -Laravel's query builder syntax. - -This section includes examples on the following operators: -TODO - +``Illuminate\Support\Facades\DB`` facade and compose your query. + +This section includes query builder examples for the following operator +categories: + +- Where (TODO: reword this) +- Logical conditionals (orWhere, whereNot, and And) +- Nested logic groups +- Range (whereBetween, whereDate) +- Check for ``null`` values (whereNull) +- Array operations (whereIn, ...) +- Pattern search (like) +- Retrieve distinct values +- Aggregations Where Method Example ~~~~~~~~~~~~~~~~~~~~ @@ -140,13 +127,6 @@ results returned from the query: IMDB Votes: 1521105 Plot: Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency. - Title: The Shawshank Redemption - Year: 1994 - Runtime: 142 - IMDB Rating: 9.3 - IMDB Votes: 1513145 - Plot: Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency. - Title: The Real Miyagi Year: 2015 Runtime: 90 @@ -154,6 +134,8 @@ results returned from the query: IMDB Votes: 41 Plot: The life of the greatest karate master of a generation. + + Logical Conditional Operation Examples ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -163,52 +145,389 @@ the following logical conditional operations: - **OR** by chaining the ``orWhere()`` function - **AND** by chaining another ``where()`` function - **NOT** which uses the ``whereNot()`` function +- Nested logic groups - Nesting logical conditionals: year 2010 OR - back to the future or year 1955 + + .. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query orWhere + :end-before: end query orWhere + +AND - rating > 8.5 and year < 1940 + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query andWhere + :end-before: end query andWhere + + +NOT - imdb.rating not > 2 (or <= 2) + + .. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query whereNot + :end-before: end query whereNot + + + +Nested logical groups +year rating is > 8.5 and (year is 1986 or 1996) + + .. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query nestedLogical + :end-before: end query nestedLogical + + +- Range and types (whereBetween, whereNull, whereIn, whereDate) + +whereBetween - rating 9 and 10 .. io-code-block:: .. input:: /includes/query-builder/MovieController.php :language: php :dedent: - :start-after: begin query orWhere - :end-before: end query orWhere + :start-after: begin query whereBetween + :end-before: end query whereBetween .. output:: :language: none :visible: false - + Title: Hollywood + Year: 1980 + Runtime: 60 + IMDB Rating: 9.1 + IMDB Votes: 511 + Plot: The definitive documentary about the American silent film industry. -AND - rating == 8.2 and duration < 30 + Title: Cosmos + Year: 1980 + Runtime: 60 + IMDB Rating: 9.3 + IMDB Votes: 17174 + Plot: Astronomer Carl Sagan leads us on an engaging guided tour of the various elements and cosmological theories of the universe. -NOT - type != movie + ... +whereNull runtime: null -The following example shows how to use the following logical conditional -operations: +.. io-code-block:: + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query whereNull + :end-before: end query whereNull -``where()`` method retrieve -documents from the ``movies`` collection that contain a ``imdb.votes`` field -value of ``350``. Click the :guilabel:`{+code-output-label+}` button to see the -results returned from the query: + .. output:: + :language: none + :visible: false -- Range and types (whereBetween, whereNull, whereDate) + Title: The Secret of the Magic Gourd + Year: 2007 + Runtime: + IMDB Rating: 5.6 + IMDB Votes: 340 + Plot: A boy learns the meaning of work after a magic gourd grants him anything he wants. -whereBetween - rating 9 and 10 -whereNull runtime: null -whereDate released between 2002 2005 + Title: Jekyll + Year: 2007 + Runtime: + IMDB Rating: 8.2 + IMDB Votes: 6248 + Plot: London, 2007. Tom Jackman is the only living descendent of Dr. Jekyll and Mr. Hyde. He has made a deal with his dark side: a body share. What Mr. Hyde doesn't know is that Tom has a family.... + + + +whereIn +[Toy Story, Shrek 2, Johny English] + +.. io-code-block:: + + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query whereIn + :end-before: end query whereIn + + .. output:: + :language: none + :visible: false + + Title: Toy Story + Year: 1995 + Runtime: 81 + IMDB Rating: 8.3 + IMDB Votes: 542659 + Plot: A cowboy doll is profoundly threatened and jealous when a new spaceman figure supplants him as top toy in a boy's room. + + Title: Johnny English + Year: 2003 + Runtime: 87 + IMDB Rating: 6.1 + IMDB Votes: 107074 + Plot: After a sudden attack on the MI5, Johnny English, Britain's most confident yet unintelligent spy, becomes Britain's only spy. + Title: Shrek 2 + Year: 2004 + Runtime: 93 + IMDB Rating: 7.2 + IMDB Votes: 283852 + Plot: Princess Fiona's parents invite her and Shrek to dinner to celebrate her marriage. If only they knew the newlyweds were both ogres. -regex: -"The Lord of % ..." +whereDate released on Jan 15, 2010 +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query whereDate + :end-before: end query whereDate +- Pattern search (like) +%spider%man% + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query like + :end-before: end query like + +Matches results such as "Spider-Man", "Spider-Man 2", and "Kiss of the Spider Woman" + +- Retrieve distinct values + +distinct: year + +TODO: figure out how to print in the view + +distinct where: imdb.rating > 9 , distinct year + +TODO: figure out how to print in the view + +groupBy - TODO + +- Aggregations (is this in Query Builder?) +TODO + +.. _laravel-modify-results-query-builder: + +Modify Results +-------------- + +Modify results: orderBy, skip, projection, projection with pagination + +orderby + +back to the future% rating descending + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query orderBy + :end-before: end query orderBy + +Title: Back to the Future +Year: 1985 +Runtime: 116 +IMDB Rating: 8.5 +IMDB Votes: 636511 +Plot: A young man is accidentally sent 30 years into the past in a time-traveling DeLorean invented by his friend, Dr. Emmett Brown, and must make sure his high-school-age parents unite in order to save his own existence. +Title: Back to the Future Part II +Year: 1989 +Runtime: 108 +IMDB Rating: 7.8 +IMDB Votes: 292539 +Plot: After visiting 2015, Marty McFly must repeat his visit to 1955 to prevent disastrous changes to 1985... without interfering with his first trip. +Title: Back to the Future Part III +Year: 1990 +Runtime: 118 +IMDB Rating: 7.4 +IMDB Votes: 242390 +Plot: Enjoying a peaceable existence in 1885, Doctor Emmet Brown is about to be killed by Buford "Mad Dog" Tannen. Marty McFly travels back in time to save his friend. + +skip +like star trek% skip 7 +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query skip + :end-before: end query skip + + + +To learn more about pagination, see +`Paginating Query Builder Results `__ +in the Laravel documentation. + + +.. _laravel-mongodb-read-query-builder: + +MongoDB Query Operators +----------------------- + +- General - Exists, All, Size, Type, Mod + +Exists + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query exists + :end-before: end query exists + +All (contains all fields) + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query all + :end-before: end query all + +Size (match size of array for a field) + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query size + :end-before: end query size + +Type + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query type + :end-before: end query type + + +Mod - an even year + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query modulo + :end-before: end query modulo + +- Regex - "Match Regular Expressions" + +regex: +"^the lord of .*" +matches results such as "The Lord of the Rings: ..." + +``use MongoDB\BSON\Regex;`` + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query whereRegex + :end-before: end query whereRegex + +- Raw expressionsa + +whereRaw([ +query +])->get() +returns collection of models + +maybe a query like { status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] } +that combines multiple things + + +- Array - ElemMatch "Element Match" + +TODO: Match cast member + +https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/ + + +- Geospatial - near, geowithin, geointersects, geonear + +- Projection + +projection + +.. io-code-block:: + + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query projection + :end-before: end query projection + + .. output:: + :language: json + :visible: false + + [ + { + "_id": { ... }, + "title": "City Lights" + "cast": [ + "Florence Lee", + "Harry Myers", + "Al Ernest Garcia" + ], + }, + { + "_id": { ... }, + "title": "Modern Times", + "cast": [ + "Paulette Goddard", + "Henry Bergman", + "Tiny Sandford" + ] + }, + { + "_id": { ... }, + "title": "Casablanca" + "cast": [ + "Ingrid Bergman", + "Paul Henreid", + "Claude Rains" + ], + }, + ... + ] + +projection with pagination + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query projection with pagination + :end-before: end query projection with pagination + +- Cursor timeout + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query cursor timeout + :end-before: end query cursor timeout + +Note this is in seconds rather than milliseconds. + +.. _laravel-mongodb-write-query-builder: + +MongoDB Write Operations +------------------------ + +- Upsert +- Increment/ decrement +- Modify array values - push, pull +- Remove a field from a document - Unset + From 20073560418731b0d027bcb6eaa88e3c179ab764 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 21 Mar 2024 11:34:34 -0400 Subject: [PATCH 05/36] WIP --- .../query-builder/MovieController.php | 664 ++++++++++++++++++ docs/query-builder.txt | 245 +++++-- 2 files changed, 858 insertions(+), 51 deletions(-) create mode 100644 docs/includes/query-builder/MovieController.php diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php new file mode 100644 index 000000000..fd583459c --- /dev/null +++ b/docs/includes/query-builder/MovieController.php @@ -0,0 +1,664 @@ +collection('movies') + ->where('imdb.rating', 9.3) + ->get(); + // end query where + + return $movies; + } + + private function runOrWhere() { + // begin query orWhere + $movies = DB::connection('mongodb') + ->collection('movies') + ->where('year', 1955) + ->orWhere('title', 'Back to the Future') + ->get(); + // end query orWhere + + return $movies; + } + private function runAndWhere() { + // begin query andWhere + $movies = DB::connection('mongodb') + ->collection('movies') + ->where('imdb.rating', '>', 8.5) + ->where('year', '<', 1940) + ->get(); + // end query andWhere + + return $movies; + } + private function runNestedLogical() { + // begin query nestedLogical + $movies = DB::connection('mongodb') + ->collection('movies') + ->where('imdb.rating', '>', 8.5) + ->where(function ($query) { + return $query + ->where('year', 1986) + ->orWhere('year', 1996); + })->get(); + // end query nestedLogical + + return $movies; + } + private function runWhereNot() { + // begin query whereNot + $movies = DB::connection('mongodb') + ->collection('movies') + ->whereNot('imdb.rating', '>', 2) + ->get(); + // end query whereNot + + return $movies; + } + + private function runWhereBetween() { + // begin query runWhere + $movies = DB::connection('mongodb') + ->collection('movies') + ->whereBetween('imdb.rating', [9, 10]) + ->get(); + // end query runWhere + + return $movies; + } + + private function runWhereNull() { + // begin query whereNull + $movies = DB::connection('mongodb') + ->collection('movies') + ->whereNull('runtime') + ->get(); + // end query whereNull + + return $movies; + } + + private function runWhereDate() { + // begin query whereDate + $movies = DB::connection('mongodb') + ->collection('movies') + ->whereDate('released', '2010-1-15') + ->get(); + // begin query whereDate + + return $movies; + } + + private function runRegex() { + // begin query whereRegex + $movies = DB::connection('mongodb') + ->collection('movies') + ->where('title', 'REGEX', new Regex('^the lord of .*', 'i' )) + ->get(); + // end query whereRegex + + return $movies; + } + + + private function runWhereIn() { + // begin query whereIn + $movies = DB::collection('movies') + ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) + ->get(); + // end query whereIn + + return $movies; + } + + private function runLike() { + // begin query like + $movies = DB::collection('movies') + ->where('title', 'like', '%spider%man%') + ->get(); + // begin query like + + return $movies; + } + + private function runExists() { + // begin query exists + $result = DB::collection('movies') + ->exists('title', 'I\'m a Cyborg, But That\'s OK'); + // begin query exists + + print_r($result); + return null; + } + + + private function runAll() { + // begin query all + $movies = DB::collection('movies') + ->where('movies', 'all', ['title', 'rated', 'imdb.rating' ]) + ->getl(); + // begin query all + + return $movies; + } + + + private function runSize() { + // begin query size + $result = DB::collection('movies') + ->where('directors', 'size', 5) + ->get(); + // begin query size + + print_r($result); + return null; + } + + private function runType() { + // begin query type + $movies = DB::collection('movies') + ->where('released', 'type', 4) + ->get(); + // begin query type + + return $movies; + } + + + private function runMod() { + // begin query modulo + $movies = DB::collection('movies') + ->where('year', 'mod', [2, 0]) + ->get(); + // begin query modulo + + return $movies; + } + + private function runDistinct() { + // begin query distinct + $result = DB::collection('movies') + ->distinct('year')->get(); + // begin query distinct + print_r($result); + return null; + } + + private function runWhereDistinct() { + // begin query where distinct + $result = DB::collection('movies') + ->where('imdb.rating', '>', 9) + ->distinct('year') + ->get(); + // begin query where distinct + print_r($result); + return null; + } + + private function runOrderBy() { + // begin query orderBy + $movies = DB::collection('movies') + ->where('title', 'like', 'back to the future%') + ->orderBy('imdb.rating', 'desc') + ->get(); + // end query orderBy + + return $movies; + } + + private function runGroupBy() { + // begin query groupBy + $result = DB::collection('movies') + ->groupBy('year') + ->get(['title']); + // end query groupBy + + print_r($result); + return null; + } + + private function runAggCount() { + // begin aggregation count + $result = DB::collection('movies') + ->count(); + // end aggregation count + + print_r($result); + return null; + } + + private function runAggMax() { + // begin aggregation max + $result = DB::collection('movies') + ->max('runtime'); + // end aggregation max + + print_r($result); + return null; + } + + private function runAggMin() { + // begin aggregation min + $result = DB::collection('movies') + ->min('year'); + // end aggregation min + + print_r($result); + return null; + } + + private function runAggAvg() { + // begin aggregation avg + $result = DB::collection('movies') + ->avg('imdb.rating'); + // end aggregation avg + + print_r($result); + return null; + } + + private function runAggSum() { + // begin aggregation sum + $result = DB::collection('movies') + ->sum('imdb.votes'); + // end aggregation sum + + print_r($result); + return null; + } + + private function runAggWithFilter() { + // begin aggregation with filter + $result = DB::collection('movies') + ->where('year', '>', 2000) + ->avg('imdb.rating'); + // end aggregation with filter + + print_r($result); + return null; + } + + private function runSkip() { + // begin query skip + $movies = DB::collection('movies') + ->where('title', 'like', 'star trek%') + ->orderBy('year', 'asc') + ->skip(4) + ->get(); + // end query skip + + return $movies; + } + + + private function runWhereRaw() { + // begin query raw + $movies = DB::collection('movies') + ->whereRaw([ + 'imdb.votes' => ['$gte' => 1000 ], + '$or' => [ + ['imdb.rating' => ['$gt' => 7]], + ['directors' => ['$in' => [ 'Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini' ]]] + ] + ]) + ->get(); + // end query raw + + return $movies; + } + + private function runElemMatch() { + // begin query elemMatch + $movies = DB::collection('movies') + ->where('writers', 'elemMatch', ['$eq' => 'Lana Wilson', '$eq' => 'Maya Forbes']) + ->get(); + // end query elemMatch + + return $movies; + } + + + private function runNear() { + // begin query near + $results = DB::collection('theaters') + ->where('location.geo', 'near', [ + '$geometry' => [ + 'type' => 'Point', + 'coordinates' => [ + -86.6423, 33.6054 + ], + ], + '$maxDistance' => 50, + ])->get(); + // end query near + + print_r($results); + return null; + } + + private function runGeoWithin() { + // begin query geoWithin + $results = DB::collection('theaters') + ->where('location.geo', 'geoWithin', [ + '$geometry' => [ + 'type' => 'Polygon', + 'coordinates' => [ + [ + [-72, 40], [-74, 41], [-72, 39], [-72, 40] + ], + ]]])->get(); + // end query geoWithin + + print_r($results); + return null; + } + + + private function runGeoIntersects() { + // begin query geoIntersects + $results = DB::collection('theaters') + ->where('location.geo', 'geoIntersects', [ + '$geometry' => [ + 'type' => 'LineString', + 'coordinates' => [ + [-73.600525, 40.74416], + [-72.600525, 40.74416], + ], + ], + ])->get(); + // end query geoIntersects + + print_r($results); + return null; + } + + private function runGeoNear() { + // begin query geoNear + $results = DB::collection('theaters') + ->whereRaw([ + function($collection) { + return $collection->aggregate([ + [ + '$geoNear' => [ + 'near' => [ + 'type' => 'Point', + 'coordinates' => [ -118.34, 34.10 ], + ], + 'distanceField' => 'dist.calculated', + 'maxDistance' => 500, + 'includeLocs' => 'dist.location', + 'spherical' => true, + ] + ] + ]); + }])->get(); + // end query geoNear + + print_r($results); + return null; + } + + private function runAggregate() { + $results = DB::collection('theaters') + ->whereRaw([ + function($collection) { + return $collection->aggregate([ + [ '$match' => [ 'theaterId', '>=', 8013] ]]); + + }])->get(); + + print_r($results); + return null; + } + + private function runProjection() { + // begin query projection + $result = DB::collection('movies') + ->where('imdb.rating', '>', 8.5) + ->project([ + 'title' => 1, + 'cast' => ['$slice' => [1, 3]], + ]) + ->get(); + // end query projection + print_r($result->toJson()); + return null; + } + + private function runProjectionWithPagination() { + // begin query projection with pagination + $resultsPerPage = 15; + $projectionFields = ['title', 'runtime', 'imdb.rating']; + + $movies = DB::collection('movies') + ->paginate($resultsPerPage, $projectionFields) + ->get(); + // end query projection with pagination + + return $movies; + + } + + private function runCursorTimeout() { + // begin query cursor timeout + $movies = DB::collection('movies') + ->timeout(2) // value in seconds + ->where('year', 2001) + ->get(); + // end query cursor timeout + + return $movies; + } + + private function runUpsert() { + // begin upsert + $movies = DB::collection('movies') + ->where('title', 'Will Hunting') + ->update([ + 'plot' => 'An autobiographical movie', + 'year' => 1998, + 'writers' => [ 'Will Hunting' ], + ], + ['upsert' => true]); + // end upsert + + return $movies; + } + + private function runIncrement() { + // begin increment + $result = DB::collection('movies') + ->where('title', 'Field of Dreams') + ->increment('imdb.votes', 3000); + // end increment + + print_r($result); + return $result; + } + + private function runDecrement() { + // begin decrement + $result = DB::collection('movies') + ->where('title', 'Sharknado') + ->decrement('imdb.rating', 0.2); + // end decrement + + print_r($result); + return $result; + } + + + private function runPush() { + // begin push + $result = DB::collection('movies') + ->where('title', 'Office Space') + ->push('cast', 'Gary Cole'); + // end push + + print_r($result); + return $result; + } + + + private function runPull() { + // begin pull + $result = DB::collection('movies') + ->where('title', 'Iron Man') + ->pull('genres', 'Adventure'); + // end pull + + print_r($result); + return $result; + } + + private function runUnset() { + // begin unset + $result = DB::collection('movies') + ->where('title', 'Final Accord') + ->unset('tomatoes.viewer'); + // end unset + + print_r($result); + return $result; + } + + /** + * Display the specified resource. + */ + public function show() + { + + $result = null; + //$result = $this->runWhere(); + + //$result = $this->runOrWhere(); + + //$result = $this->runAndWhere(); + + // $result = $this->runNestedLogical(); + + //$result = $this->runWhereNot(); + + //$result = $this->runWhereBetween(); + + //$result = $this->runWhereNull(); + + //$result = $this->runWhereDate(); + + //$result = $this->runLike(); + + //$result = $this->runExists(); + + //$result = $this->runAll(); + + //$result = $this->runSize(); + + //$result = $this->runType(); + + //$result = $this->runMod(); + + //$result = $this->runRegex(); + + //$result = $this->runWhereRaw(); + + //$result = $this->runElemMatch(); + + //$result = $this->runNear(); + + //$result = $this->runGeoWithin(); + + //$result = $this->runGeoIntersects(); + + //$result = $this->runGeoNear(); + //TODO $result = $this->runAggregate(); + + //$result = $this->runWhereIn(); + + //$result = $this->runDistinct(); + + //$result = $this->runWhereDistinct(); + + //$result = $this->runOrderBy(); + + //$result = $this->runGroupBy(); + + //$result = $this->runAggCount(); + + //$result = $this->runAggMax(); + + //$result = $this->runAggMin(); + + //$result = $this->runAggAvg(); + + //$result = $this->runAggSum(); + + //$result = $this->runAggWithFilter(); + + //$result = $this->runSkip(); + + //$result = Movie::where('year', 1999)->get(); //first(); + + //$result = $this->runProjection(); + + //$result = $this->runCursorTimeout(); + + //$result = $this->runUpsert(); + + //$result = $this->runIncrement(); + + //$result = $this->runDecrement(); + + //$result = $this->runPush(); + + //$result = $this->runPull(); + + $result = $this->runUnset(); + + //$result = Movie::first(); + return view('browse_movies', [ + 'movies' => $result + ]); + } + + /** + * Show the form for editing the specified resource. + */ + public function edit(Movie $movie) {} + + /** + * Update the specified resource in storage. + */ + public function update(Request $request, Movie $movie) {} + + /** + * Remove the specified resource from storage. + */ + public function destroy(Movie $movie) {} +} diff --git a/docs/query-builder.txt b/docs/query-builder.txt index f9dc276da..83f146274 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -54,10 +54,6 @@ This guide shows examples of the following types of query builder operations: - :ref:`laravel-mongodb-read-query-builder` - :ref:`laravel-mongodb-write-query-builder` -- Write operations - - link to - - Before You Get Started ---------------------- @@ -134,8 +130,6 @@ results returned from the query: IMDB Votes: 41 Plot: The life of the greatest karate master of a generation. - - Logical Conditional Operation Examples ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -147,8 +141,7 @@ the following logical conditional operations: - **NOT** which uses the ``whereNot()`` function - Nested logic groups -- Nesting logical conditionals: year 2010 - +- Nesting logical conditionals: OR - back to the future or year 1955 @@ -175,8 +168,6 @@ NOT - imdb.rating not > 2 (or <= 2) :start-after: begin query whereNot :end-before: end query whereNot - - Nested logical groups year rating is > 8.5 and (year is 1986 or 1996) @@ -186,7 +177,6 @@ year rating is > 8.5 and (year is 1986 or 1996) :start-after: begin query nestedLogical :end-before: end query nestedLogical - - Range and types (whereBetween, whereNull, whereIn, whereDate) whereBetween - rating 9 and 10 @@ -248,7 +238,6 @@ whereNull runtime: null Plot: London, 2007. Tom Jackman is the only living descendent of Dr. Jekyll and Mr. Hyde. He has made a deal with his dark side: a body share. What Mr. Hyde doesn't know is that Tom has a family.... - whereIn [Toy Story, Shrek 2, Johny English] @@ -295,8 +284,6 @@ whereDate released on Jan 15, 2010 :start-after: begin query whereDate :end-before: end query whereDate - - - Pattern search (like) %spider%man% @@ -312,55 +299,118 @@ Matches results such as "Spider-Man", "Spider-Man 2", and "Kiss of the Spider Wo distinct: year -TODO: figure out how to print in the view +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query distinct + :end-before: end query distinct distinct where: imdb.rating > 9 , distinct year -TODO: figure out how to print in the view +groupBy + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query groupBy + :end-before: end query groupBy -groupBy - TODO - Aggregations (is this in Query Builder?) -TODO + +count + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin aggregation count + :end-before: end aggregation count + +max + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin aggregation max + :end-before: end aggregation max + +min + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin aggregation min + :end-before: end aggregation min + +avg + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin aggregation avg + :end-before: end aggregation avg + +sum + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin aggregation sum + :end-before: end aggregation sum + +with filter + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin aggregation with filter + :end-before: end aggregation with filter + .. _laravel-modify-results-query-builder: Modify Results -------------- -Modify results: orderBy, skip, projection, projection with pagination +Modify results: orderBy, skip, projection, projection with pagination orderby back to the future% rating descending -.. literalinclude:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query orderBy - :end-before: end query orderBy - -Title: Back to the Future -Year: 1985 -Runtime: 116 -IMDB Rating: 8.5 -IMDB Votes: 636511 -Plot: A young man is accidentally sent 30 years into the past in a time-traveling DeLorean invented by his friend, Dr. Emmett Brown, and must make sure his high-school-age parents unite in order to save his own existence. -Title: Back to the Future Part II -Year: 1989 -Runtime: 108 -IMDB Rating: 7.8 -IMDB Votes: 292539 -Plot: After visiting 2015, Marty McFly must repeat his visit to 1955 to prevent disastrous changes to 1985... without interfering with his first trip. -Title: Back to the Future Part III -Year: 1990 -Runtime: 118 -IMDB Rating: 7.4 -IMDB Votes: 242390 -Plot: Enjoying a peaceable existence in 1885, Doctor Emmet Brown is about to be killed by Buford "Mad Dog" Tannen. Marty McFly travels back in time to save his friend. +.. io-code-block:: + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query orderBy + :end-before: end query orderBy + + .. output:: + :language: none + :copyable: false + + Title: Back to the Future + Year: 1985 + Runtime: 116 + IMDB Rating: 8.5 + IMDB Votes: 636511 + Plot: A young man is accidentally sent 30 years into the past in a time-traveling DeLorean invented by his friend, Dr. Emmett Brown, and must make sure his high-school-age parents unite in order to save his own existence. + Title: Back to the Future Part II + Year: 1989 + Runtime: 108 + IMDB Rating: 7.8 + IMDB Votes: 292539 + Plot: After visiting 2015, Marty McFly must repeat his visit to 1955 to prevent disastrous changes to 1985... without interfering with his first trip. + Title: Back to the Future Part III + Year: 1990 + Runtime: 118 + IMDB Rating: 7.4 + IMDB Votes: 242390 + Plot: Enjoying a peaceable existence in 1885, Doctor Emmet Brown is about to be killed by Buford "Mad Dog" Tannen. Marty McFly travels back in time to save his friend. skip like star trek% skip 7 + .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: @@ -368,12 +418,10 @@ like star trek% skip 7 :end-before: end query skip - To learn more about pagination, see `Paginating Query Builder Results `__ in the Laravel documentation. - .. _laravel-mongodb-read-query-builder: MongoDB Query Operators @@ -419,8 +467,8 @@ Mod - an even year .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: - :start-after: begin query modulo - :end-before: end query modulo + :start-after: begin query modulo + :end-before: end query modulo - Regex - "Match Regular Expressions" @@ -443,19 +491,71 @@ query ])->get() returns collection of models -maybe a query like { status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] } -that combines multiple things +equivalent of db.movies.find({ 'imdb.votes': { $gte: 1000 }, $or: [{ "imdb.rating": { $gt: 7 }, directors: { $in: [ "Yasujiro Ozu", "Sofia Coppola", "Federico Fellini" ] } }]}); +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query whereRaw + :end-before: end query whereRaw - Array - ElemMatch "Element Match" -TODO: Match cast member +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query elemMatch + :end-before: end query elemMatch https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/ - - Geospatial - near, geowithin, geointersects, geonear +- Near + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query geoNear + :end-before: end query geoNear + +https://www.mongodb.com/docs/manual/reference/operator/query/near/ + +You may need to create the index +db.theaters.createIndex({"location.geo": "2dsphere"}); + +geoWithin + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query geoWithin + :end-before: end query geoWithin + +uses https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/crud/read-operations/geo/#query-within-a-range + +geoIntersects + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query geoIntersects + :end-before: end query geoIntersects + + +db.theaters.find({ "location.geo": { $geoIntersects: { $geometry: { type: "LineString", coordinates: [[-73.600525, 40.74416], [-72.600525, 40.74416]] } } } } ) + +geoNear +- provides distance from point which $near does not + +db.theaters.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [-118.34, 34.10] }, distanceField: "dist.calculated", maxDistance: 500, includeLocs: "dist.location", spherical: true } }] ) + +not sure syntax is correct in the controller; no error thrown + + +https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear/ + + - Projection projection @@ -527,7 +627,50 @@ MongoDB Write Operations ------------------------ - Upsert + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin upsert + :end-before: end upsert + - Increment/ decrement + +Field of Dreams votes 127k rating 7.5 + + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin increment + :end-before: end increment + +decrement + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin decrement + :end-before: end decrement + - Modify array values - push, pull + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin push + :end-before: end push + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin pull + :end-before: end pull + - Remove a field from a document - Unset +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin unset + :end-before: end unset From 1de9614a5ddad6aedf94b986084e0a9bf69510a8 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 21 Mar 2024 11:57:27 -0400 Subject: [PATCH 06/36] fix RST --- .../query-builder/MovieController.php | 48 +++++++++---------- docs/query-builder.txt | 32 ++++++------- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index fd583459c..74112b7ef 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -98,7 +98,7 @@ private function runWhereNull() { // begin query whereNull $movies = DB::connection('mongodb') ->collection('movies') - ->whereNull('runtime') + ->whereNull('runtime') ->get(); // end query whereNull @@ -109,9 +109,9 @@ private function runWhereDate() { // begin query whereDate $movies = DB::connection('mongodb') ->collection('movies') - ->whereDate('released', '2010-1-15') + ->whereDate('released', '2010-1-15') ->get(); - // begin query whereDate + // end query whereDate return $movies; } @@ -143,7 +143,7 @@ private function runLike() { $movies = DB::collection('movies') ->where('title', 'like', '%spider%man%') ->get(); - // begin query like + // end query like return $movies; } @@ -152,7 +152,7 @@ private function runExists() { // begin query exists $result = DB::collection('movies') ->exists('title', 'I\'m a Cyborg, But That\'s OK'); - // begin query exists + // end query exists print_r($result); return null; @@ -164,7 +164,7 @@ private function runAll() { $movies = DB::collection('movies') ->where('movies', 'all', ['title', 'rated', 'imdb.rating' ]) ->getl(); - // begin query all + // end query all return $movies; } @@ -175,7 +175,7 @@ private function runSize() { $result = DB::collection('movies') ->where('directors', 'size', 5) ->get(); - // begin query size + // end query size print_r($result); return null; @@ -186,7 +186,7 @@ private function runType() { $movies = DB::collection('movies') ->where('released', 'type', 4) ->get(); - // begin query type + // end query type return $movies; } @@ -197,7 +197,7 @@ private function runMod() { $movies = DB::collection('movies') ->where('year', 'mod', [2, 0]) ->get(); - // begin query modulo + // end query modulo return $movies; } @@ -206,7 +206,7 @@ private function runDistinct() { // begin query distinct $result = DB::collection('movies') ->distinct('year')->get(); - // begin query distinct + // end query distinct print_r($result); return null; } @@ -217,7 +217,7 @@ private function runWhereDistinct() { ->where('imdb.rating', '>', 9) ->distinct('year') ->get(); - // begin query where distinct + // end query where distinct print_r($result); return null; } @@ -323,7 +323,7 @@ private function runWhereRaw() { $movies = DB::collection('movies') ->whereRaw([ 'imdb.votes' => ['$gte' => 1000 ], - '$or' => [ + '$or' => [ ['imdb.rating' => ['$gt' => 7]], ['directors' => ['$in' => [ 'Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini' ]]] ] @@ -372,7 +372,7 @@ private function runGeoWithin() { 'coordinates' => [ [ [-72, 40], [-74, 41], [-72, 39], [-72, 40] - ], + ], ]]])->get(); // end query geoWithin @@ -471,7 +471,7 @@ private function runCursorTimeout() { $movies = DB::collection('movies') ->timeout(2) // value in seconds ->where('year', 2001) - ->get(); + ->get(); // end query cursor timeout return $movies; @@ -496,7 +496,7 @@ private function runIncrement() { // begin increment $result = DB::collection('movies') ->where('title', 'Field of Dreams') - ->increment('imdb.votes', 3000); + ->increment('imdb.votes', 3000); // end increment print_r($result); @@ -507,7 +507,7 @@ private function runDecrement() { // begin decrement $result = DB::collection('movies') ->where('title', 'Sharknado') - ->decrement('imdb.rating', 0.2); + ->decrement('imdb.rating', 0.2); // end decrement print_r($result); @@ -519,7 +519,7 @@ private function runPush() { // begin push $result = DB::collection('movies') ->where('title', 'Office Space') - ->push('cast', 'Gary Cole'); + ->push('cast', 'Gary Cole'); // end push print_r($result); @@ -531,7 +531,7 @@ private function runPull() { // begin pull $result = DB::collection('movies') ->where('title', 'Iron Man') - ->pull('genres', 'Adventure'); + ->pull('genres', 'Adventure'); // end pull print_r($result); @@ -542,7 +542,7 @@ private function runUnset() { // begin unset $result = DB::collection('movies') ->where('title', 'Final Accord') - ->unset('tomatoes.viewer'); + ->unset('tomatoes.viewer'); // end unset print_r($result); @@ -563,19 +563,19 @@ public function show() //$result = $this->runAndWhere(); // $result = $this->runNestedLogical(); - - //$result = $this->runWhereNot(); + + //$result = $this->runWhereNot(); //$result = $this->runWhereBetween(); //$result = $this->runWhereNull(); //$result = $this->runWhereDate(); - + //$result = $this->runLike(); - + //$result = $this->runExists(); - + //$result = $this->runAll(); //$result = $this->runSize(); diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 83f146274..af78d305a 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -145,11 +145,11 @@ the following logical conditional operations: OR - back to the future or year 1955 - .. literalinclude:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query orWhere - :end-before: end query orWhere +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query orWhere + :end-before: end query orWhere AND - rating > 8.5 and year < 1940 @@ -162,20 +162,20 @@ AND - rating > 8.5 and year < 1940 NOT - imdb.rating not > 2 (or <= 2) - .. literalinclude:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query whereNot - :end-before: end query whereNot +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query whereNot + :end-before: end query whereNot Nested logical groups year rating is > 8.5 and (year is 1986 or 1996) - .. literalinclude:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query nestedLogical - :end-before: end query nestedLogical +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query nestedLogical + :end-before: end query nestedLogical - Range and types (whereBetween, whereNull, whereIn, whereDate) @@ -387,7 +387,7 @@ back to the future% rating descending .. output:: :language: none - :copyable: false + :visible: false Title: Back to the Future Year: 1985 From 3c658c33545ea5f4ac1d5d8229471c3ec6bc0873 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 21 Mar 2024 12:24:05 -0400 Subject: [PATCH 07/36] fix RST --- docs/query-builder.txt | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index af78d305a..08a15100a 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -180,6 +180,7 @@ year rating is > 8.5 and (year is 1986 or 1996) - Range and types (whereBetween, whereNull, whereIn, whereDate) whereBetween - rating 9 and 10 + .. io-code-block:: .. input:: /includes/query-builder/MovieController.php @@ -285,6 +286,7 @@ whereDate released on Jan 15, 2010 :end-before: end query whereDate - Pattern search (like) + %spider%man% .. literalinclude:: /includes/query-builder/MovieController.php @@ -496,8 +498,8 @@ equivalent of db.movies.find({ 'imdb.votes': { $gte: 1000 }, $or: [{ "imdb.ratin .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: - :start-after: begin query whereRaw - :end-before: end query whereRaw + :start-after: begin query raw + :end-before: end query raw - Array - ElemMatch "Element Match" @@ -642,16 +644,16 @@ Field of Dreams votes 127k rating 7.5 .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: - :start-after: begin increment - :end-before: end increment + :start-after: begin increment + :end-before: end increment decrement .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: - :start-after: begin decrement - :end-before: end decrement + :start-after: begin decrement + :end-before: end decrement - Modify array values - push, pull @@ -673,4 +675,4 @@ decrement :language: php :dedent: :start-after: begin unset - :end-before: end unset + :end-before: end unset From c886c366c086fff4e600d702b9fcc02aaf2fd5d3 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 21 Mar 2024 16:41:13 -0400 Subject: [PATCH 08/36] WIP --- .../query-builder/MovieController.php | 22 +- docs/query-builder.txt | 250 ++++++++++++++---- 2 files changed, 205 insertions(+), 67 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index 74112b7ef..10c017e55 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -87,7 +87,7 @@ private function runWhereBetween() { // begin query runWhere $movies = DB::connection('mongodb') ->collection('movies') - ->whereBetween('imdb.rating', [9, 10]) + ->whereBetween('imdb.rating', [9, 9.5]) ->get(); // end query runWhere @@ -111,7 +111,7 @@ private function runWhereDate() { ->collection('movies') ->whereDate('released', '2010-1-15') ->get(); - // end query whereDate + // begin query whereDate return $movies; } @@ -143,7 +143,7 @@ private function runLike() { $movies = DB::collection('movies') ->where('title', 'like', '%spider%man%') ->get(); - // end query like + // begin query like return $movies; } @@ -152,7 +152,7 @@ private function runExists() { // begin query exists $result = DB::collection('movies') ->exists('title', 'I\'m a Cyborg, But That\'s OK'); - // end query exists + // begin query exists print_r($result); return null; @@ -164,7 +164,7 @@ private function runAll() { $movies = DB::collection('movies') ->where('movies', 'all', ['title', 'rated', 'imdb.rating' ]) ->getl(); - // end query all + // begin query all return $movies; } @@ -175,7 +175,7 @@ private function runSize() { $result = DB::collection('movies') ->where('directors', 'size', 5) ->get(); - // end query size + // begin query size print_r($result); return null; @@ -186,7 +186,7 @@ private function runType() { $movies = DB::collection('movies') ->where('released', 'type', 4) ->get(); - // end query type + // begin query type return $movies; } @@ -197,7 +197,7 @@ private function runMod() { $movies = DB::collection('movies') ->where('year', 'mod', [2, 0]) ->get(); - // end query modulo + // begin query modulo return $movies; } @@ -206,7 +206,7 @@ private function runDistinct() { // begin query distinct $result = DB::collection('movies') ->distinct('year')->get(); - // end query distinct + // begin query distinct print_r($result); return null; } @@ -217,7 +217,7 @@ private function runWhereDistinct() { ->where('imdb.rating', '>', 9) ->distinct('year') ->get(); - // end query where distinct + // begin query where distinct print_r($result); return null; } @@ -639,7 +639,7 @@ public function show() //$result = $this->runPull(); - $result = $this->runUnset(); + //$result = $this->runUnset(); //$result = Movie::first(); return view('browse_movies', [ diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 08a15100a..c3633d0a6 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -9,7 +9,7 @@ Query Builder :values: tutorial .. meta:: - :keywords: code example + :keywords: code example, aggregation .. contents:: On this page :local: @@ -30,6 +30,7 @@ interface and syntax. {+odm-short+} extends Laravel's query builder and Eloquent ORM, both of which can run similar database operations. To learn more about retrieving documents by using Eloquent models, see :ref:`laravel-fundamentals-retrieve`. + TODO: link to Eloquent Models page once merged Laravel provides a **facade** to access the query builder class ``DB``, which lets you perform database operations. Facades are static interfaces to @@ -58,8 +59,8 @@ Before You Get Started ---------------------- To run the code examples in this guide, complete the -:ref:`Quick Start ` tutorial and paste the example code -in the ``show()`` controller method. +:ref:`Quick Start ` tutorial to configure a web +application and run the example code from a controller method. .. TODO: this requirement can be removed after https://jira.mongodb.org/browse/DOCSP-37770 is completed @@ -68,34 +69,35 @@ in the ``show()`` controller method. file, which accesses Eloquent ORM operation results, with the `browse_movies_array.blade.php `__ file to access the ar +To perform read and write operations by using the query builder, import the +``Illuminate\Support\Facades\DB`` facade and compose your query. + .. _laravel-retrieve-query-builder: Retrieve Documents ------------------ -To retrieve documents by using the query builder, import the -``Illuminate\Support\Facades\DB`` facade and compose your query. - -This section includes query builder examples for the following operator -categories: +This section includes query builder examples for read operations in the +following operator categories: -- Where (TODO: reword this) -- Logical conditionals (orWhere, whereNot, and And) -- Nested logic groups -- Range (whereBetween, whereDate) -- Check for ``null`` values (whereNull) -- Array operations (whereIn, ...) -- Pattern search (like) +- :ref:`Where method ` +- Logical conditionals +- Ranges and type checks +- Array operations +- Pattern searches - Retrieve distinct values - Aggregations +.. _laravel-query-builder-where-example: + Where Method Example ~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``where()`` method retrieve -documents from the ``movies`` collection that contain a ``imdb.votes`` field -value of ``350``. Click the :guilabel:`{+code-output-label+}` button to see the -results returned from the query: +The following example shows how to use the ``where()`` query +builder method to retrieve documents from the ``movies`` collection +that contain a ``imdb.votes`` field value of ``350``. Click the +:guilabel:`{+code-output-label+}` button to see the results returned +by the query: .. io-code-block:: @@ -133,17 +135,21 @@ results returned from the query: Logical Conditional Operation Examples ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The examples in this section show query builder syntax you can use to perform -the following logical conditional operations: +The examples in this section show the query builder syntax you +can use to perform the following logical conditional operations: - **OR** by chaining the ``orWhere()`` function - **AND** by chaining another ``where()`` function - **NOT** which uses the ``whereNot()`` function -- Nested logic groups +- Nested logical operator groups -- Nesting logical conditionals: +Logical OR Example +^^^^^^^^^^^^^^^^^^ -OR - back to the future or year 1955 +The following example shows how to chain the ``orWhere()`` +query builder method to retrieve documents from the +``movies`` collection that either match the ``year`` +value of "1955" or match the title "Back to the Future": .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -151,7 +157,14 @@ OR - back to the future or year 1955 :start-after: begin query orWhere :end-before: end query orWhere -AND - rating > 8.5 and year < 1940 +Logical AND Example +^^^^^^^^^^^^^^^^^^^ + +The following example shows how to chain the ``where()`` +query builder method to retrieve documents from the +``movies`` collection that match both an ``imdb.rating`` +value greater than "8.5" and a ``year`` value of less than +"1940": .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -159,8 +172,14 @@ AND - rating > 8.5 and year < 1940 :start-after: begin query andWhere :end-before: end query andWhere +Logical NOT Example +^^^^^^^^^^^^^^^^^^^ -NOT - imdb.rating not > 2 (or <= 2) +The following example shows how to chain the ``where()`` +query builder method to retrieve documents from the +``movies`` collection that match both an ``imdb.rating`` +value greater than "8.5" and a ``year`` value of less than +"1940": .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -168,8 +187,16 @@ NOT - imdb.rating not > 2 (or <= 2) :start-after: begin query whereNot :end-before: end query whereNot -Nested logical groups -year rating is > 8.5 and (year is 1986 or 1996) +Nested Logical Operator Group Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to chain the ``where()`` +query builder method to retrieve documents from the +``movies`` collection that match both of the following +conditions: + +- ``imdb.rating`` value is greater than 8.5 +- ``year`` value is either 1986 or 1996 .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -177,9 +204,25 @@ year rating is > 8.5 and (year is 1986 or 1996) :start-after: begin query nestedLogical :end-before: end query nestedLogical -- Range and types (whereBetween, whereNull, whereIn, whereDate) +Ranges and Type Checks +~~~~~~~~~~~~~~~~~~~~~~ + +The examples in this section show the query builder syntax you +can use to perform to match values by using the following range +queries and type check operations: -whereBetween - rating 9 and 10 +- Values within a numerical range +- Empty or null values +- One or more values of a set +- Dates + +Numerical Range Example +^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to use the ``whereBetween()`` +query builder method to retrieve documents from the +``movies`` collection that contain an ``imdb.rating`` value +between "9" and "9.5": .. io-code-block:: @@ -209,8 +252,13 @@ whereBetween - rating 9 and 10 ... +Empty or Null Value Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^ -whereNull runtime: null +The following example shows how to use the ``whereNull()`` +query builder method to retrieve documents from the +``movies`` collection that omit a ``runtime`` value +or field. .. io-code-block:: @@ -238,9 +286,17 @@ whereNull runtime: null IMDB Votes: 6248 Plot: London, 2007. Tom Jackman is the only living descendent of Dr. Jekyll and Mr. Hyde. He has made a deal with his dark side: a body share. What Mr. Hyde doesn't know is that Tom has a family.... +.. seealso:: + + The ``exists()`` MongoDB operation performs the same query. -whereIn -[Toy Story, Shrek 2, Johny English] +One or More Values of a Set Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to use the ``whereIn()`` +query builder method to retrieve documents from the +``movies`` collection that match at least one of the +``title`` values in the specified set. .. io-code-block:: @@ -275,9 +331,13 @@ whereIn IMDB Votes: 283852 Plot: Princess Fiona's parents invite her and Shrek to dinner to celebrate her marriage. If only they knew the newlyweds were both ogres. +Dates Example +^^^^^^^^^^^^^ -whereDate released on Jan 15, 2010 - +The following example shows how to use the ``whereDate()`` +query builder method to retrieve documents from the +``movies`` collection that match the specified date of +"2010-1-15" in the ``released`` field: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -285,21 +345,45 @@ whereDate released on Jan 15, 2010 :start-after: begin query whereDate :end-before: end query whereDate -- Pattern search (like) +Pattern Search Example +^^^^^^^^^^^^^^^^^^^^^^ -%spider%man% +To specify a pattern, use the ``%`` symbol to match +zero or more characters or the ``_`` symbol to match +any single character. -.. literalinclude:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query like - :end-before: end query like +The following example shows how to use the ``like()`` +query builder method to retrieve documents from the +``movies`` collection that match the specified pattern: + +.. io-code-block:: -Matches results such as "Spider-Man", "Spider-Man 2", and "Kiss of the Spider Woman" + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query like + :end-before: end query like -- Retrieve distinct values + .. output:: + :language: none + :visible: false + + Title: Kiss of the Spider Woman + ... + + Title: Spider-Man + ... -distinct: year + Title: Spider-Man 2 + ... + + +Retrieve Distinct Values +~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``distinct()`` +query builder method to retrieve all the different values +of the ``year`` field for documents in the ``movies`` collections. .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -307,9 +391,27 @@ distinct: year :start-after: begin query distinct :end-before: end query distinct -distinct where: imdb.rating > 9 , distinct year +Aggregations +~~~~~~~~~~~~ + +The examples in this section show the query builder syntax you +can use to perform aggregations, a set of calculations on the +query results, to return the following information: + +- Results Grouped by Common Field Values +- Number of Results +- Maximum Value of a Field +- Minimum Value of a Field +- Average Value of a Field +- Summed Value of a Field +- Aggregation on Matched Results -groupBy +Results Grouped by Common Field Values Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to use the ``groupBy()`` +query builder method to retrieve documents as +TODO: fix this .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -317,10 +419,13 @@ groupBy :start-after: begin query groupBy :end-before: end query groupBy +Number of Results Example +^^^^^^^^^^^^^^^^^^^^^^^^^ -- Aggregations (is this in Query Builder?) - -count +The following example shows how to use the ``count()`` +query builder method to return the number of results +from a query that matches the entire ``movies`` +collection: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -328,7 +433,13 @@ count :start-after: begin aggregation count :end-before: end aggregation count -max +Maximum Value of a Field Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to use the ``max()`` +query builder method to return the highest numerical +value of the ``runtime`` field from the entire +``movies`` collection: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -336,7 +447,13 @@ max :start-after: begin aggregation max :end-before: end aggregation max -min +Minimum Value of a Field Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to use the ``min()`` +query builder method to return the lowest numerical +value of the ``year`` field from the entire ``movies`` +collection: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -344,7 +461,13 @@ min :start-after: begin aggregation min :end-before: end aggregation min -avg +Average Value of a Field Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to use the ``avg()`` +query builder method to return the numerical average, or +arithmetic mean, of the ``imdb.rating`` values from +the entire ``movies`` collection. .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -352,7 +475,14 @@ avg :start-after: begin aggregation avg :end-before: end aggregation avg -sum +Summed Value of a Field Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to use the ``sum()`` +query builder method to return the numerical total of +the ``imdb.votes`` values from the entire ``movies`` +collection: + .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -360,7 +490,14 @@ sum :start-after: begin aggregation sum :end-before: end aggregation sum -with filter + +Aggregation on Matched Results Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following example shows how to use the ``sum()`` +query builder method to return the numerical total of +the ``imdb.votes`` values from movies released in +after the year "2000": .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -368,7 +505,6 @@ with filter :start-after: begin aggregation with filter :end-before: end aggregation with filter - .. _laravel-modify-results-query-builder: Modify Results @@ -397,12 +533,14 @@ back to the future% rating descending IMDB Rating: 8.5 IMDB Votes: 636511 Plot: A young man is accidentally sent 30 years into the past in a time-traveling DeLorean invented by his friend, Dr. Emmett Brown, and must make sure his high-school-age parents unite in order to save his own existence. + Title: Back to the Future Part II Year: 1989 Runtime: 108 IMDB Rating: 7.8 IMDB Votes: 292539 Plot: After visiting 2015, Marty McFly must repeat his visit to 1955 to prevent disastrous changes to 1985... without interfering with his first trip. + Title: Back to the Future Part III Year: 1990 Runtime: 118 From 2ab0c4673f464a372218e999336fa29f02471af4 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 21 Mar 2024 16:45:56 -0400 Subject: [PATCH 09/36] WIP --- .../query-builder/MovieController.php | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index 10c017e55..a2e0021c2 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -84,12 +84,12 @@ private function runWhereNot() { } private function runWhereBetween() { - // begin query runWhere + // begin query runWhereBetween $movies = DB::connection('mongodb') ->collection('movies') ->whereBetween('imdb.rating', [9, 9.5]) ->get(); - // end query runWhere + // end query runWhereBetween return $movies; } @@ -111,7 +111,7 @@ private function runWhereDate() { ->collection('movies') ->whereDate('released', '2010-1-15') ->get(); - // begin query whereDate + // end query whereDate return $movies; } @@ -143,7 +143,7 @@ private function runLike() { $movies = DB::collection('movies') ->where('title', 'like', '%spider%man%') ->get(); - // begin query like + // end query like return $movies; } @@ -152,7 +152,7 @@ private function runExists() { // begin query exists $result = DB::collection('movies') ->exists('title', 'I\'m a Cyborg, But That\'s OK'); - // begin query exists + // end query exists print_r($result); return null; @@ -164,7 +164,7 @@ private function runAll() { $movies = DB::collection('movies') ->where('movies', 'all', ['title', 'rated', 'imdb.rating' ]) ->getl(); - // begin query all + // end query all return $movies; } @@ -175,7 +175,7 @@ private function runSize() { $result = DB::collection('movies') ->where('directors', 'size', 5) ->get(); - // begin query size + // end query size print_r($result); return null; @@ -186,7 +186,7 @@ private function runType() { $movies = DB::collection('movies') ->where('released', 'type', 4) ->get(); - // begin query type + // end query type return $movies; } @@ -197,7 +197,7 @@ private function runMod() { $movies = DB::collection('movies') ->where('year', 'mod', [2, 0]) ->get(); - // begin query modulo + // end query modulo return $movies; } @@ -206,7 +206,7 @@ private function runDistinct() { // begin query distinct $result = DB::collection('movies') ->distinct('year')->get(); - // begin query distinct + // end query distinct print_r($result); return null; } @@ -217,7 +217,7 @@ private function runWhereDistinct() { ->where('imdb.rating', '>', 9) ->distinct('year') ->get(); - // begin query where distinct + // end query where distinct print_r($result); return null; } @@ -607,7 +607,7 @@ public function show() //$result = $this->runOrderBy(); - //$result = $this->runGroupBy(); + $result = $this->runGroupBy(); //$result = $this->runAggCount(); From ea3dd8e4a9fdd917fd17c5122246d47470466f50 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 21 Mar 2024 17:02:43 -0400 Subject: [PATCH 10/36] fix --- docs/includes/query-builder/MovieController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index a2e0021c2..47bbbd916 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -84,12 +84,12 @@ private function runWhereNot() { } private function runWhereBetween() { - // begin query runWhereBetween + // begin query whereBetween $movies = DB::connection('mongodb') ->collection('movies') ->whereBetween('imdb.rating', [9, 9.5]) ->get(); - // end query runWhereBetween + // end query whereBetween return $movies; } From 1e0ce7f7db945402ffd53fd00c2f58eb0e170ece Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 21 Mar 2024 18:28:51 -0400 Subject: [PATCH 11/36] wip --- .../query-builder/MovieController.php | 18 +- docs/query-builder.txt | 191 +++++++++++------- 2 files changed, 127 insertions(+), 82 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index 47bbbd916..6d2f6ed02 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -151,7 +151,7 @@ private function runLike() { private function runExists() { // begin query exists $result = DB::collection('movies') - ->exists('title', 'I\'m a Cyborg, But That\'s OK'); + ->exists('random_review', true); // end query exists print_r($result); @@ -457,13 +457,13 @@ private function runProjectionWithPagination() { $resultsPerPage = 15; $projectionFields = ['title', 'runtime', 'imdb.rating']; - $movies = DB::collection('movies') - ->paginate($resultsPerPage, $projectionFields) - ->get(); + $result = DB::collection('movies') + ->orderBy('imdb.votes', 'desc') + ->paginate($resultsPerPage, $projectionFields); // end query projection with pagination - return $movies; - + print_r($result->toJson()); + return null; } private function runCursorTimeout() { @@ -574,7 +574,7 @@ public function show() //$result = $this->runLike(); - //$result = $this->runExists(); + $result = $this->runExists(); //$result = $this->runAll(); @@ -607,7 +607,7 @@ public function show() //$result = $this->runOrderBy(); - $result = $this->runGroupBy(); + //$result = $this->runGroupBy(); //$result = $this->runAggCount(); @@ -627,6 +627,8 @@ public function show() //$result = $this->runProjection(); + //$result = $this->runProjectionWithPagination(); + //$result = $this->runCursorTimeout(); //$result = $this->runUpsert(); diff --git a/docs/query-builder.txt b/docs/query-builder.txt index c3633d0a6..6db523dca 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -510,11 +510,24 @@ after the year "2000": Modify Results -------------- -Modify results: orderBy, skip, projection, projection with pagination +This section includes query builder examples for the +following functions that modify the order and format +of query results: -orderby +- Order results by the value of a field +- Omit a specified number of results +- Show a subset of fields and array values in the results +- Paginate the results -back to the future% rating descending + + +Order Results Example +~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``orderBy()`` +query builder method to arrange the results that match +the filter specified in the ``title`` field by the +``imdb.rating`` value in descending order: .. io-code-block:: .. input:: /includes/query-builder/MovieController.php @@ -528,28 +541,24 @@ back to the future% rating descending :visible: false Title: Back to the Future - Year: 1985 - Runtime: 116 IMDB Rating: 8.5 - IMDB Votes: 636511 - Plot: A young man is accidentally sent 30 years into the past in a time-traveling DeLorean invented by his friend, Dr. Emmett Brown, and must make sure his high-school-age parents unite in order to save his own existence. + ... Title: Back to the Future Part II - Year: 1989 - Runtime: 108 IMDB Rating: 7.8 - IMDB Votes: 292539 - Plot: After visiting 2015, Marty McFly must repeat his visit to 1955 to prevent disastrous changes to 1985... without interfering with his first trip. + ... Title: Back to the Future Part III - Year: 1990 - Runtime: 118 IMDB Rating: 7.4 - IMDB Votes: 242390 - Plot: Enjoying a peaceable existence in 1885, Doctor Emmet Brown is about to be killed by Buford "Mad Dog" Tannen. Marty McFly travels back in time to save his friend. + ... -skip -like star trek% skip 7 +Omit a Specified Number of Results Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``skip()`` +query builder method to omit the first "4" results that +match the filter speficied in the ``title`` field, +sorted by the ``year`` value in descending order: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -558,14 +567,102 @@ like star trek% skip 7 :end-before: end query skip +Show a Subset of Fields and Array Values in the Results Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``project()`` +query builder method to match documents that contain an +``imdb.rating`` value higher than "8.5" and return results +that only the following field values: + +- ``title`` field +- Second through the fourth values of the ``cast`` array, if they exist +- ``_id`` field, which is automatically included + +TODO: describe output + +.. io-code-block:: + + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query projection + :end-before: end query projection + + .. output:: + :language: json + :visible: false + + [ + { + "_id": { ... }, + "title": "City Lights" + "cast": [ + "Florence Lee", + "Harry Myers", + "Al Ernest Garcia" + ], + }, + { + "_id": { ... }, + "title": "Modern Times", + "cast": [ + "Paulette Goddard", + "Henry Bergman", + "Tiny Sandford" + ] + }, + { + "_id": { ... }, + "title": "Casablanca" + "cast": [ + "Ingrid Bergman", + "Paul Henreid", + "Claude Rains" + ], + }, + ... + ] + +Paginate the Results Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``paginate()`` +query builder method to divide the entire ``movie`` +collection into discrete result sets of 15 documents. +The example also includes a sort order to arrange the +results by the ``imdb.votes`` field in descending order +and a projection to include only specific fields in +the results. + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query projection with pagination + :end-before: end query projection with pagination + To learn more about pagination, see `Paginating Query Builder Results `__ in the Laravel documentation. .. _laravel-mongodb-read-query-builder: -MongoDB Query Operators ------------------------ +MongoDB Query Operations +------------------------ + +This section includes query builder examples that +show how to use the following MongoDB-specific query +operations: + +- Check whether a document with a field exists +- Check whether a document contains all the fields +- Match documents that contain a specific number of elements in an array +- Match documents that contain a specific data type in a field +- Match documents that match a computed modulo value +- Match documents that match a regular expression +- Run MQL +- elemMatch +- geospatial - General - Exists, All, Size, Type, Mod @@ -624,7 +721,7 @@ matches results such as "The Lord of the Rings: ..." :start-after: begin query whereRegex :end-before: end query whereRegex -- Raw expressionsa +- Raw expressions whereRaw([ query @@ -696,60 +793,6 @@ not sure syntax is correct in the controller; no error thrown https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear/ -- Projection - -projection - -.. io-code-block:: - - .. input:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query projection - :end-before: end query projection - - .. output:: - :language: json - :visible: false - - [ - { - "_id": { ... }, - "title": "City Lights" - "cast": [ - "Florence Lee", - "Harry Myers", - "Al Ernest Garcia" - ], - }, - { - "_id": { ... }, - "title": "Modern Times", - "cast": [ - "Paulette Goddard", - "Henry Bergman", - "Tiny Sandford" - ] - }, - { - "_id": { ... }, - "title": "Casablanca" - "cast": [ - "Ingrid Bergman", - "Paul Henreid", - "Claude Rains" - ], - }, - ... - ] - -projection with pagination - -.. literalinclude:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query projection with pagination - :end-before: end query projection with pagination - Cursor timeout From 7f9c68fa42bb7fdc7f48a6f65f45392000ba448b Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 22 Mar 2024 10:57:44 -0400 Subject: [PATCH 12/36] wip --- docs/query-builder.txt | 163 ++++++++++++++++++++++++++++++++--------- 1 file changed, 130 insertions(+), 33 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 6db523dca..2e6f2a61f 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -81,12 +81,11 @@ This section includes query builder examples for read operations in the following operator categories: - :ref:`Where method ` -- Logical conditionals -- Ranges and type checks -- Array operations -- Pattern searches -- Retrieve distinct values -- Aggregations +- :ref:`Logical conditionals ` +- :ref:`Ranges and type checks ` +- :ref:`Pattern searches ` +- :ref:`Retrieve distinct values ` +- :ref:`Aggregations ` .. _laravel-query-builder-where-example: @@ -132,6 +131,8 @@ by the query: IMDB Votes: 41 Plot: The life of the greatest karate master of a generation. +.. _laravel-query-builder-logical-operations: + Logical Conditional Operation Examples ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -204,6 +205,8 @@ conditions: :start-after: begin query nestedLogical :end-before: end query nestedLogical +.. _laravel-query-builder-range-type: + Ranges and Type Checks ~~~~~~~~~~~~~~~~~~~~~~ @@ -345,8 +348,10 @@ query builder method to retrieve documents from the :start-after: begin query whereDate :end-before: end query whereDate +.. _laravel-query-builder-pattern: + Pattern Search Example -^^^^^^^^^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~~~~~~~~~ To specify a pattern, use the ``%`` symbol to match zero or more characters or the ``_`` symbol to match @@ -377,6 +382,7 @@ query builder method to retrieve documents from the Title: Spider-Man 2 ... +.. _laravel-query-builder-distinct: Retrieve Distinct Values ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -391,6 +397,9 @@ of the ``year`` field for documents in the ``movies`` collections. :start-after: begin query distinct :end-before: end query distinct + +.. _laravel-query-builder-aggregations: + Aggregations ~~~~~~~~~~~~ @@ -576,11 +585,9 @@ query builder method to match documents that contain an that only the following field values: - ``title`` field -- Second through the fourth values of the ``cast`` array, if they exist +- ``cast`` field, including only the second through the fourth values of the array if they exist - ``_id`` field, which is automatically included - -TODO: describe output - +- .. io-code-block:: .. input:: /includes/query-builder/MovieController.php @@ -647,15 +654,15 @@ in the Laravel documentation. .. _laravel-mongodb-read-query-builder: -MongoDB Query Operations ------------------------- +MongoDB Read Operations +----------------------- This section includes query builder examples that show how to use the following MongoDB-specific query operations: -- Check whether a document with a field exists -- Check whether a document contains all the fields +- Match documetns that contain a field +- Match documents that contain all specified fields - Match documents that contain a specific number of elements in an array - Match documents that contain a specific data type in a field - Match documents that match a computed modulo value @@ -666,7 +673,12 @@ operations: - General - Exists, All, Size, Type, Mod -Exists +Contains a Field Example +~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``exists()`` +query builder method to match documents that contain the +field ``random_review``: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -674,7 +686,13 @@ Exists :start-after: begin query exists :end-before: end query exists -All (contains all fields) +Contains All Fields Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``all`` +query operator with the ``where()`` query builder +method to match documents that contain all the +specified fields: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -682,7 +700,13 @@ All (contains all fields) :start-after: begin query all :end-before: end query all -Size (match size of array for a field) +Match Array Size Example +~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to pass the ``size`` +query operator with the ``where()`` query builder +method to match documents that contain a ``directors`` +field that contains an array of exactly "5" elements: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -690,7 +714,13 @@ Size (match size of array for a field) :start-after: begin query size :end-before: end query size -Type +Match Data Type Example +~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to pass the ``type`` +query operator with the ``where()`` query builder +method to match documents that contain a ``directors`` +field that contains an array of exactly "5" elements: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -746,21 +776,38 @@ equivalent of db.movies.find({ 'imdb.votes': { $gte: 1000 }, $or: [{ "imdb.ratin https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/ -- Geospatial - near, geowithin, geointersects, geonear + +Geospatial Operations +~~~~~~~~~~~~~~~~~~~~~ + +The examples in this section show the query builder syntax you +can use to perform geospatial queries on GeoJSON or coordinate +pair data to retrieve the following types of locations: + +- Near a position +- Within an area +- Intersecting a geometry +- Proximity data for nearby matches + +Near a Position Example +~~~~~~~~~~~~~~~~~~~~~~~ - Near .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: - :start-after: begin query geoNear - :end-before: end query geoNear + :start-after: begin query near + :end-before: end query near https://www.mongodb.com/docs/manual/reference/operator/query/near/ You may need to create the index db.theaters.createIndex({"location.geo": "2dsphere"}); +Within an Area Example +~~~~~~~~~~~~~~~~~~~~~~ + geoWithin .. literalinclude:: /includes/query-builder/MovieController.php @@ -771,6 +818,9 @@ geoWithin uses https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/crud/read-operations/geo/#query-within-a-range +Intersecting a Geometry Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + geoIntersects .. literalinclude:: /includes/query-builder/MovieController.php @@ -779,15 +829,18 @@ geoIntersects :start-after: begin query geoIntersects :end-before: end query geoIntersects - db.theaters.find({ "location.geo": { $geoIntersects: { $geometry: { type: "LineString", coordinates: [[-73.600525, 40.74416], [-72.600525, 40.74416]] } } } } ) -geoNear -- provides distance from point which $near does not +Proximity Data for Nearby Matches Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -db.theaters.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [-118.34, 34.10] }, distanceField: "dist.calculated", maxDistance: 500, includeLocs: "dist.location", spherical: true } }] ) +geoNear -not sure syntax is correct in the controller; no error thrown +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query geoNear + :end-before: end query geoNear https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear/ @@ -809,7 +862,24 @@ Note this is in seconds rather than milliseconds. MongoDB Write Operations ------------------------ -- Upsert +- Upsert a document +- Increment a numerical value +- Decrement a numerical value +- Add an array element +- Remove a value from an array +- Remove a field from a document + +Upsert a Document Example +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``update()`` +query builder method and ``upsert`` option to update +the matching document or insert one with the specified +data if it does not exist. When setting the ``upsert`` +option to ``true``, if the document does not exist, +the command inserts both the data and the ``title`` +field and value specified in the ``where()`` query +operation: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -817,10 +887,12 @@ MongoDB Write Operations :start-after: begin upsert :end-before: end upsert -- Increment/ decrement - -Field of Dreams votes 127k rating 7.5 +Increment a Numerical Value Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The following example shows how to use the ``increment()`` +query builder method to add "3000" to the value of +the ``imdb.votes`` field in the matched document: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -828,7 +900,12 @@ Field of Dreams votes 127k rating 7.5 :start-after: begin increment :end-before: end increment -decrement +Decrement a Numerical Value Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``decrement()`` +query builder method to subtract "0.2" from the value of +the ``imdb.rating`` field in the matched document: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -838,19 +915,39 @@ decrement - Modify array values - push, pull +Add an Array Element Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``push()`` +query builder method to add "Gary Cole" to the ``cast`` +array field in the matched document: + .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: :start-after: begin push :end-before: end push +Remove an Array Element Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``pull()`` +query builder method to remove the "Adventure" value +from the ``genres`` field from the document matched +by the query: + .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: :start-after: begin pull :end-before: end pull -- Remove a field from a document - Unset +Remove a Field Example +~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to use the ``unset()`` +query builder method to remove the ``tomatoes.viewer`` +field and value from the document matched by the query: .. literalinclude:: /includes/query-builder/MovieController.php :language: php From 64e321ba884f0ae571c2d6c0dde543b7b4c68f0d Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 22 Mar 2024 13:57:46 -0400 Subject: [PATCH 13/36] WIP --- docs/query-builder.txt | 133 +++++++++++++++++++++++++++++++---------- 1 file changed, 101 insertions(+), 32 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 2e6f2a61f..262334a30 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -665,11 +665,12 @@ operations: - Match documents that contain all specified fields - Match documents that contain a specific number of elements in an array - Match documents that contain a specific data type in a field -- Match documents that match a computed modulo value +- Match documents that contain a computed modulo value - Match documents that match a regular expression -- Run MQL -- elemMatch -- geospatial +- Run Mongo Query API queries +- Match documents that contain array elements +- Specify a cursor timeout +- Match Locations by Using Geospatial Operations - General - Exists, All, Size, Type, Mod @@ -686,6 +687,10 @@ field ``random_review``: :start-after: begin query exists :end-before: end query exists +To learn more about this query operator, see +:manual:`$exists ` +in the {+server-docs-name+}. + Contains All Fields Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -700,6 +705,10 @@ specified fields: :start-after: begin query all :end-before: end query all +To learn more about this query operator, see +:manual:`$all ` +in the {+server-docs-name+}. + Match Array Size Example ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -714,6 +723,10 @@ field that contains an array of exactly "5" elements: :start-after: begin query size :end-before: end query size +To learn more about this query operator, see +:manual:`$size ` +in the {+server-docs-name+}. + Match Data Type Example ~~~~~~~~~~~~~~~~~~~~~~~ @@ -728,8 +741,18 @@ field that contains an array of exactly "5" elements: :start-after: begin query type :end-before: end query type +To learn more about the type codes and query operator, see +:manual:`$type ` +in the {+server-docs-name+}. -Mod - an even year +Match a Value Computed with Modulo Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to pass the ``mod`` +query operator with the ``where()`` query builder +method to match documents by using the expression +``year % 2 == 0``, which matches even values for +the ``year`` field: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -737,13 +760,17 @@ Mod - an even year :start-after: begin query modulo :end-before: end query modulo -- Regex - "Match Regular Expressions" +To learn more about this query operator, see +:manual:`$mod ` +in the {+server-docs-name+}. -regex: -"^the lord of .*" -matches results such as "The Lord of the Rings: ..." +Match a Regular Expression +~~~~~~~~~~~~~~~~~~~~~~~~~~ -``use MongoDB\BSON\Regex;`` +The following example shows how to pass the ``REGEX`` +query operator with the ``where()`` query builder +method to match documents that contain a ``title`` +field that matches the specified regular expression: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -751,14 +778,16 @@ matches results such as "The Lord of the Rings: ..." :start-after: begin query whereRegex :end-before: end query whereRegex -- Raw expressions +To learn more about regular expression queries in MongoDB, see +:manual:`$regex ` +in the {+server-docs-name+}. -whereRaw([ -query -])->get() -returns collection of models +Run Mongo Query API Queries Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -equivalent of db.movies.find({ 'imdb.votes': { $gte: 1000 }, $or: [{ "imdb.rating": { $gt: 7 }, directors: { $in: [ "Yasujiro Ozu", "Sofia Coppola", "Federico Fellini" ] } }]}); +The following example shows how to use the ``whereRaw()`` +query builder method to run a query written by using +MongoDB Query API syntax: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -766,6 +795,29 @@ equivalent of db.movies.find({ 'imdb.votes': { $gte: 1000 }, $or: [{ "imdb.ratin :start-after: begin query raw :end-before: end query raw +The following code shows the equivalent MongoDB query: + +.. code-block:: + + db.movies.find({ + "imdb.votes": { $gte: 1000 }, + $or: [{ + imdb.rating: { $gt: 7 }, + directors: { $in: [ "Yasujiro Ozu", "Sofia Coppola", "Federico Fellini" ] } + }]}); + + +Match Array Elements Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows how to pass the ``elemMatch`` +query operator with the ``where()`` query builder +method to match documents that contain a at least one +array element that matches at least one of the conditions +in the specified query: + +field that matches the specified regular expression: + - Array - ElemMatch "Element Match" .. literalinclude:: /includes/query-builder/MovieController.php @@ -774,11 +826,27 @@ equivalent of db.movies.find({ 'imdb.votes': { $gte: 1000 }, $or: [{ "imdb.ratin :start-after: begin query elemMatch :end-before: end query elemMatch -https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/ +To learn more about regular expression queries in MongoDB, see +the :manual:`$elemMatch operator ` +in the {+server-docs-name+}. -Geospatial Operations -~~~~~~~~~~~~~~~~~~~~~ +Specify Cursor Timeout Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +TODO: + +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query cursor timeout + :end-before: end query cursor timeout + +Note this is in seconds rather than milliseconds. + + +Match Locations by Using Geospatial Operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The examples in this section show the query builder syntax you can use to perform geospatial queries on GeoJSON or coordinate @@ -792,7 +860,9 @@ pair data to retrieve the following types of locations: Near a Position Example ~~~~~~~~~~~~~~~~~~~~~~~ -- Near +The following example shows how to use the ``near()`` +query builder method to match documents that contain the +field ``random_review``: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -846,17 +916,6 @@ geoNear https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear/ - -- Cursor timeout - -.. literalinclude:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query cursor timeout - :end-before: end query cursor timeout - -Note this is in seconds rather than milliseconds. - .. _laravel-mongodb-write-query-builder: MongoDB Write Operations @@ -869,6 +928,8 @@ MongoDB Write Operations - Remove a value from an array - Remove a field from a document +.. _laravel-mongodb-query-builder-upsert: + Upsert a Document Example ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -887,6 +948,8 @@ operation: :start-after: begin upsert :end-before: end upsert +.. _laravel-mongodb-query-builder-increment: + Increment a Numerical Value Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -900,6 +963,8 @@ the ``imdb.votes`` field in the matched document: :start-after: begin increment :end-before: end increment +.. _laravel-mongodb-query-builder-decrement: + Decrement a Numerical Value Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -913,7 +978,7 @@ the ``imdb.rating`` field in the matched document: :start-after: begin decrement :end-before: end decrement -- Modify array values - push, pull +.. _laravel-mongodb-query-builder-push: Add an Array Element Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -928,6 +993,8 @@ array field in the matched document: :start-after: begin push :end-before: end push +.. _laravel-mongodb-query-builder-pull: + Remove an Array Element Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -942,6 +1009,8 @@ by the query: :start-after: begin pull :end-before: end pull +.. _laravel-mongodb-query-builder-unset: + Remove a Field Example ~~~~~~~~~~~~~~~~~~~~~~ From d34a04d48e98422e9d804dfa60d73292aa7ecb18 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 22 Mar 2024 15:35:47 -0400 Subject: [PATCH 14/36] WIP --- docs/query-builder.txt | 53 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 10 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 262334a30..5b99bfbf2 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -528,7 +528,7 @@ of query results: - Show a subset of fields and array values in the results - Paginate the results - + .. _laravel-query-builder-orderby: Order Results Example ~~~~~~~~~~~~~~~~~~~~~ @@ -561,6 +561,8 @@ the filter specified in the ``title`` field by the IMDB Rating: 7.4 ... + .. _laravel-query-builder-skip: + Omit a Specified Number of Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -575,6 +577,7 @@ sorted by the ``year`` value in descending order: :start-after: begin query skip :end-before: end query skip + .. _laravel-query-builder-project: Show a Subset of Fields and Array Values in the Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -631,6 +634,8 @@ that only the following field values: ... ] + .. _laravel-query-builder-paginate: + Paginate the Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -674,6 +679,8 @@ operations: - General - Exists, All, Size, Type, Mod + .. _laravel-query-builder-exists: + Contains a Field Example ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -691,6 +698,8 @@ To learn more about this query operator, see :manual:`$exists ` in the {+server-docs-name+}. + .. _laravel-query-builder-all: + Contains All Fields Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -709,6 +718,8 @@ To learn more about this query operator, see :manual:`$all ` in the {+server-docs-name+}. + .. _laravel-query-builder-size: + Match Array Size Example ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -727,6 +738,8 @@ To learn more about this query operator, see :manual:`$size ` in the {+server-docs-name+}. + .. _laravel-query-builder-type: + Match Data Type Example ~~~~~~~~~~~~~~~~~~~~~~~ @@ -745,6 +758,8 @@ To learn more about the type codes and query operator, see :manual:`$type ` in the {+server-docs-name+}. + .. _laravel-query-builder-mod: + Match a Value Computed with Modulo Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -764,6 +779,8 @@ To learn more about this query operator, see :manual:`$mod ` in the {+server-docs-name+}. + .. _laravel-query-builder-regex: + Match a Regular Expression ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -782,6 +799,8 @@ To learn more about regular expression queries in MongoDB, see :manual:`$regex ` in the {+server-docs-name+}. + .. _laravel-query-builder-whereRaw: + Run Mongo Query API Queries Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -806,6 +825,7 @@ The following code shows the equivalent MongoDB query: directors: { $in: [ "Yasujiro Ozu", "Sofia Coppola", "Federico Fellini" ] } }]}); + .. _laravel-query-builder-elemMatch: Match Array Elements Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -816,10 +836,6 @@ method to match documents that contain a at least one array element that matches at least one of the conditions in the specified query: -field that matches the specified regular expression: - -- Array - ElemMatch "Element Match" - .. literalinclude:: /includes/query-builder/MovieController.php :language: php :dedent: @@ -830,6 +846,7 @@ To learn more about regular expression queries in MongoDB, see the :manual:`$elemMatch operator ` in the {+server-docs-name+}. + .. _laravel-query-builder-cursor-timeout: Specify Cursor Timeout Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -842,8 +859,14 @@ TODO: :start-after: begin query cursor timeout :end-before: end query cursor timeout -Note this is in seconds rather than milliseconds. +.. note:: + + This setting specifies a ``maxTimeMS`` value in seconds instead of + milliseconds. To learn more about the ``maxTimeMS`` value, see + `MongoDB\Collection::find() `__ + in the PHP Library documentation. + .. _laravel-query-builder-geospatial: Match Locations by Using Geospatial Operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -857,6 +880,15 @@ pair data to retrieve the following types of locations: - Intersecting a geometry - Proximity data for nearby matches +.. important:: + + To perform GeoJSON queries in MongoDB, you must create either + ``2d`` or ``2dsphere`` index on the collection. To learn more + about these indexes, see :manual:`Geospatial Indexes ` + in the {+server-docs-name+}. + + .. _laravel-query-builder-geospatial-near: + Near a Position Example ~~~~~~~~~~~~~~~~~~~~~~~ @@ -872,8 +904,7 @@ field ``random_review``: https://www.mongodb.com/docs/manual/reference/operator/query/near/ -You may need to create the index -db.theaters.createIndex({"location.geo": "2dsphere"}); + .. _laravel-query-builder-geospatial-geoWithin: Within an Area Example ~~~~~~~~~~~~~~~~~~~~~~ @@ -888,10 +919,11 @@ geoWithin uses https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/crud/read-operations/geo/#query-within-a-range + .. _laravel-query-builder-geospatial-geoIntersects: + Intersecting a Geometry Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -geoIntersects .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -901,10 +933,11 @@ geoIntersects db.theaters.find({ "location.geo": { $geoIntersects: { $geometry: { type: "LineString", coordinates: [[-73.600525, 40.74416], [-72.600525, 40.74416]] } } } } ) + .. _laravel-query-builder-geospatial-geoNear: + Proximity Data for Nearby Matches Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -geoNear .. literalinclude:: /includes/query-builder/MovieController.php :language: php From 41cff589a831a694bd58d64a7803f389204fe96e Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 22 Mar 2024 16:56:01 -0400 Subject: [PATCH 15/36] WIP --- docs/query-builder.txt | 131 +++++++++++++++++++++++------------------ 1 file changed, 74 insertions(+), 57 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 5b99bfbf2..1aac571f4 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -30,7 +30,6 @@ interface and syntax. {+odm-short+} extends Laravel's query builder and Eloquent ORM, both of which can run similar database operations. To learn more about retrieving documents by using Eloquent models, see :ref:`laravel-fundamentals-retrieve`. - TODO: link to Eloquent Models page once merged Laravel provides a **facade** to access the query builder class ``DB``, which lets you perform database operations. Facades are static interfaces to @@ -62,13 +61,6 @@ To run the code examples in this guide, complete the :ref:`Quick Start ` tutorial to configure a web application and run the example code from a controller method. -.. - TODO: this requirement can be removed after https://jira.mongodb.org/browse/DOCSP-37770 is completed - - Replace the `browse_movie.blade.php `__ - file, which accesses Eloquent ORM operation results, with the `browse_movies_array.blade.php `__ - file to access the ar - To perform read and write operations by using the query builder, import the ``Illuminate\Support\Facades\DB`` facade and compose your query. @@ -397,7 +389,6 @@ of the ``year`` field for documents in the ``movies`` collections. :start-after: begin query distinct :end-before: end query distinct - .. _laravel-query-builder-aggregations: Aggregations @@ -415,6 +406,8 @@ query results, to return the following information: - Summed Value of a Field - Aggregation on Matched Results +.. _laravel-query-builder-aggregation-groupby: + Results Grouped by Common Field Values Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -428,6 +421,8 @@ TODO: fix this :start-after: begin query groupBy :end-before: end query groupBy +.. _laravel-query-builder-aggregation-count: + Number of Results Example ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -442,6 +437,8 @@ collection: :start-after: begin aggregation count :end-before: end aggregation count +.. _laravel-query-builder-aggregation-max: + Maximum Value of a Field Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -456,6 +453,8 @@ value of the ``runtime`` field from the entire :start-after: begin aggregation max :end-before: end aggregation max +.. _laravel-query-builder-aggregation-min: + Minimum Value of a Field Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -470,6 +469,8 @@ collection: :start-after: begin aggregation min :end-before: end aggregation min +.. _laravel-query-builder-aggregation-avg: + Average Value of a Field Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -484,6 +485,8 @@ the entire ``movies`` collection. :start-after: begin aggregation avg :end-before: end aggregation avg +.. _laravel-query-builder-aggregation-sum: + Summed Value of a Field Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -499,6 +502,7 @@ collection: :start-after: begin aggregation sum :end-before: end aggregation sum +.. _laravel-query-builder-aggregation-filter: Aggregation on Matched Results Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -523,12 +527,12 @@ This section includes query builder examples for the following functions that modify the order and format of query results: -- Order results by the value of a field -- Omit a specified number of results -- Show a subset of fields and array values in the results -- Paginate the results +- :ref:`Order results by the value of a field ` +- :ref:`Omit a specified number of results ` +- :ref:`Show a subset of fields and array values in the results ` +- :ref:`Paginate the results ` - .. _laravel-query-builder-orderby: +.. _laravel-query-builder-orderby: Order Results Example ~~~~~~~~~~~~~~~~~~~~~ @@ -539,6 +543,7 @@ the filter specified in the ``title`` field by the ``imdb.rating`` value in descending order: .. io-code-block:: + .. input:: /includes/query-builder/MovieController.php :language: php :dedent: @@ -561,7 +566,7 @@ the filter specified in the ``title`` field by the IMDB Rating: 7.4 ... - .. _laravel-query-builder-skip: +.. _laravel-query-builder-skip: Omit a Specified Number of Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -577,7 +582,7 @@ sorted by the ``year`` value in descending order: :start-after: begin query skip :end-before: end query skip - .. _laravel-query-builder-project: +.. _laravel-query-builder-project: Show a Subset of Fields and Array Values in the Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -590,7 +595,7 @@ that only the following field values: - ``title`` field - ``cast`` field, including only the second through the fourth values of the array if they exist - ``_id`` field, which is automatically included -- + .. io-code-block:: .. input:: /includes/query-builder/MovieController.php @@ -666,20 +671,18 @@ This section includes query builder examples that show how to use the following MongoDB-specific query operations: -- Match documetns that contain a field -- Match documents that contain all specified fields -- Match documents that contain a specific number of elements in an array -- Match documents that contain a specific data type in a field -- Match documents that contain a computed modulo value -- Match documents that match a regular expression -- Run Mongo Query API queries -- Match documents that contain array elements -- Specify a cursor timeout -- Match Locations by Using Geospatial Operations +- :ref:`Match documetns that contain a field ` +- :ref:`Match documents that contain all specified fields ` +- :ref:`Match documents that contain a specific number of elements in an array ` +- :ref:`Match documents that contain a specific data type in a field ` +- :ref:`Match documents that contain a computed modulo value ` +- :ref:`Match documents that match a regular expression ` +- :ref:`Run MongoDB Query API queries ` +- :ref:`Match documents that contain array elements ` +- :ref:`Specify a cursor timeout ` +- :ref:`Match Locations by Using Geospatial Operations ` -- General - Exists, All, Size, Type, Mod - - .. _laravel-query-builder-exists: +.. _laravel-query-builder-exists: Contains a Field Example ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -698,7 +701,7 @@ To learn more about this query operator, see :manual:`$exists ` in the {+server-docs-name+}. - .. _laravel-query-builder-all: +.. _laravel-query-builder-all: Contains All Fields Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -718,7 +721,7 @@ To learn more about this query operator, see :manual:`$all ` in the {+server-docs-name+}. - .. _laravel-query-builder-size: +.. _laravel-query-builder-size: Match Array Size Example ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -738,7 +741,7 @@ To learn more about this query operator, see :manual:`$size ` in the {+server-docs-name+}. - .. _laravel-query-builder-type: +.. _laravel-query-builder-type: Match Data Type Example ~~~~~~~~~~~~~~~~~~~~~~~ @@ -758,7 +761,7 @@ To learn more about the type codes and query operator, see :manual:`$type ` in the {+server-docs-name+}. - .. _laravel-query-builder-mod: +.. _laravel-query-builder-mod: Match a Value Computed with Modulo Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -779,7 +782,7 @@ To learn more about this query operator, see :manual:`$mod ` in the {+server-docs-name+}. - .. _laravel-query-builder-regex: +.. _laravel-query-builder-regex: Match a Regular Expression ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -846,7 +849,7 @@ To learn more about regular expression queries in MongoDB, see the :manual:`$elemMatch operator ` in the {+server-docs-name+}. - .. _laravel-query-builder-cursor-timeout: +.. _laravel-query-builder-cursor-timeout: Specify Cursor Timeout Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -876,8 +879,8 @@ can use to perform geospatial queries on GeoJSON or coordinate pair data to retrieve the following types of locations: - Near a position -- Within an area -- Intersecting a geometry +- Within a the boundary of a GeoJSON object +- Intersecting a GeoJSON object - Proximity data for nearby matches .. important:: @@ -887,13 +890,17 @@ pair data to retrieve the following types of locations: about these indexes, see :manual:`Geospatial Indexes ` in the {+server-docs-name+}. - .. _laravel-query-builder-geospatial-near: +To learn more about GeoJSON objects that MongoDB supports, +see :manual:`GeoJSON Objects ` +in the {+server-docs-name+}. + +.. _laravel-query-builder-geospatial-near: Near a Position Example ~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``near()`` -query builder method to match documents that contain the +The following example shows how to use the ``near`` +query operatorquery operator with the ``where()``query builder method to match documents that contain the field ``random_review``: .. literalinclude:: /includes/query-builder/MovieController.php @@ -902,14 +909,20 @@ field ``random_review``: :start-after: begin query near :end-before: end query near -https://www.mongodb.com/docs/manual/reference/operator/query/near/ +To learn more about this operator, see +:manual:`$near operator ` +in the {+server-docs-name+}. - .. _laravel-query-builder-geospatial-geoWithin: +.. _laravel-query-builder-geospatial-geoWithin: Within an Area Example ~~~~~~~~~~~~~~~~~~~~~~ -geoWithin +The following example shows how to use the ``geoWithin`` +query operator with the ``where()`` +query builder method to match documents that contain a +location within the bounds of the specified ``Polygon`` +GeoJSON object: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -917,13 +930,15 @@ geoWithin :start-after: begin query geoWithin :end-before: end query geoWithin -uses https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/crud/read-operations/geo/#query-within-a-range - .. _laravel-query-builder-geospatial-geoIntersects: Intersecting a Geometry Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The following example shows how to use the ``geoInstersects`` +query operator with the ``where()`` query builder method to +match documents that contain a location that intersects with +the specified ``LineString`` GeoJSON object: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -931,13 +946,15 @@ Intersecting a Geometry Example :start-after: begin query geoIntersects :end-before: end query geoIntersects -db.theaters.find({ "location.geo": { $geoIntersects: { $geometry: { type: "LineString", coordinates: [[-73.600525, 40.74416], [-72.600525, 40.74416]] } } } } ) - .. _laravel-query-builder-geospatial-geoNear: Proximity Data for Nearby Matches Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The following example shows how to use the ``geoNear`` +aggregation operator with the ``raw()`` query builder method +to perform an aggregation that returns metadata such as +proximity information for each match: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -945,21 +962,21 @@ Proximity Data for Nearby Matches Example :start-after: begin query geoNear :end-before: end query geoNear - -https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear/ - +To learn more about this aggregation operator, see +:manual:`$geoNear operator ` +in the {+server-docs-name+}. .. _laravel-mongodb-write-query-builder: MongoDB Write Operations ------------------------ -- Upsert a document -- Increment a numerical value -- Decrement a numerical value -- Add an array element -- Remove a value from an array -- Remove a field from a document +- :ref:`Upsert a document ` +- :ref:`Increment a numerical value ` +- :ref:`Decrement a numerical value ` +- :ref:`Add an array element ` +- :ref:`Remove a value from an array ` +- :ref:`Remove a field from a document ` .. _laravel-mongodb-query-builder-upsert: From 0a8db8c7be96e151c002b9298d4312388a2a8405 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 22 Mar 2024 17:03:57 -0400 Subject: [PATCH 16/36] fix indent --- docs/query-builder.txt | 51 ++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 1aac571f4..bc68eac94 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -211,6 +211,8 @@ queries and type check operations: - One or more values of a set - Dates +.. _laravel-query-builder-wherebetween: + Numerical Range Example ^^^^^^^^^^^^^^^^^^^^^^^ @@ -247,6 +249,8 @@ between "9" and "9.5": ... +.. _laravel-query-builder-empty-null: + Empty or Null Value Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -285,6 +289,8 @@ or field. The ``exists()`` MongoDB operation performs the same query. +.. _laravel-query-builder-wherein: + One or More Values of a Set Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -326,6 +332,8 @@ query builder method to retrieve documents from the IMDB Votes: 283852 Plot: Princess Fiona's parents invite her and Shrek to dinner to celebrate her marriage. If only they knew the newlyweds were both ogres. +.. _laravel-query-builder-wheredate: + Dates Example ^^^^^^^^^^^^^ @@ -899,8 +907,8 @@ in the {+server-docs-name+}. Near a Position Example ~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``near`` -query operatorquery operator with the ``where()``query builder method to match documents that contain the +The following example shows how to use the ``near`` query operator +with the ``where()`` query builder method to match documents that contain the field ``random_review``: .. literalinclude:: /includes/query-builder/MovieController.php @@ -930,7 +938,7 @@ GeoJSON object: :start-after: begin query geoWithin :end-before: end query geoWithin - .. _laravel-query-builder-geospatial-geoIntersects: +.. _laravel-query-builder-geospatial-geoIntersects: Intersecting a Geometry Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -983,14 +991,11 @@ MongoDB Write Operations Upsert a Document Example ~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``update()`` -query builder method and ``upsert`` option to update -the matching document or insert one with the specified -data if it does not exist. When setting the ``upsert`` -option to ``true``, if the document does not exist, -the command inserts both the data and the ``title`` -field and value specified in the ``where()`` query -operation: +The following example shows how to use the ``update()`` query builder method +and ``upsert`` option to update the matching document or insert one with the +specified data if it does not exist. When setting the ``upsert`` option to +``true``, if the document does not exist, the command inserts both the data +and the ``title`` field and value specified in the ``where()`` query operation: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -1018,9 +1023,9 @@ the ``imdb.votes`` field in the matched document: Decrement a Numerical Value Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``decrement()`` -query builder method to subtract "0.2" from the value of -the ``imdb.rating`` field in the matched document: +The following example shows how to use the ``decrement()`` query builder +method to subtract "0.2" from the value of the ``imdb.rating`` field in the +matched document: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -1033,9 +1038,8 @@ the ``imdb.rating`` field in the matched document: Add an Array Element Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``push()`` -query builder method to add "Gary Cole" to the ``cast`` -array field in the matched document: +The following example shows how to use the ``push()`` query builder method to +add "Gary Cole" to the ``cast`` array field in the matched document: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -1048,10 +1052,9 @@ array field in the matched document: Remove an Array Element Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``pull()`` -query builder method to remove the "Adventure" value -from the ``genres`` field from the document matched -by the query: +The following example shows how to use the ``pull()`` query builder method +to remove the "Adventure" value from the ``genres`` field from the document +matched by the query: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -1064,9 +1067,9 @@ by the query: Remove a Field Example ~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``unset()`` -query builder method to remove the ``tomatoes.viewer`` -field and value from the document matched by the query: +The following example shows how to use the ``unset()`` query builder method +to remove the ``tomatoes.viewer`` field and value from the document matched +by the query: .. literalinclude:: /includes/query-builder/MovieController.php :language: php From b334cfac0536a1ad1a765c7df423d233957d52c7 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 22 Mar 2024 17:13:27 -0400 Subject: [PATCH 17/36] fix RST --- docs/query-builder.txt | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index bc68eac94..bc3a9dbf1 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -604,6 +604,7 @@ that only the following field values: - ``cast`` field, including only the second through the fourth values of the array if they exist - ``_id`` field, which is automatically included + .. io-code-block:: .. input:: /includes/query-builder/MovieController.php @@ -647,7 +648,7 @@ that only the following field values: ... ] - .. _laravel-query-builder-paginate: +.. _laravel-query-builder-paginate: Paginate the Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -810,7 +811,7 @@ To learn more about regular expression queries in MongoDB, see :manual:`$regex ` in the {+server-docs-name+}. - .. _laravel-query-builder-whereRaw: +.. _laravel-query-builder-whereRaw: Run Mongo Query API Queries Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -836,7 +837,7 @@ The following code shows the equivalent MongoDB query: directors: { $in: [ "Yasujiro Ozu", "Sofia Coppola", "Federico Fellini" ] } }]}); - .. _laravel-query-builder-elemMatch: +.. _laravel-query-builder-elemMatch: Match Array Elements Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -862,7 +863,8 @@ in the {+server-docs-name+}. Specify Cursor Timeout Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -TODO: +The following example shows how to use the ``timeout()`` method +to specify a period of time to spend on cursor operations. .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -877,7 +879,7 @@ TODO: `MongoDB\Collection::find() `__ in the PHP Library documentation. - .. _laravel-query-builder-geospatial: +.. _laravel-query-builder-geospatial: Match Locations by Using Geospatial Operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -954,7 +956,7 @@ the specified ``LineString`` GeoJSON object: :start-after: begin query geoIntersects :end-before: end query geoIntersects - .. _laravel-query-builder-geospatial-geoNear: +.. _laravel-query-builder-geospatial-geoNear: Proximity Data for Nearby Matches Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From d95620e6a2e999f018dfd03b68c82676cc401995 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 22 Mar 2024 17:44:18 -0400 Subject: [PATCH 18/36] format code --- .../query-builder/MovieController.php | 588 +++++++++--------- docs/query-builder.txt | 77 ++- 2 files changed, 332 insertions(+), 333 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index 6d2f6ed02..ec194ce8a 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -1,66 +1,74 @@ collection('movies') ->where('imdb.rating', 9.3) ->get(); - // end query where - - return $movies; } - private function runOrWhere() { + private function runOrWhere() + { // begin query orWhere - $movies = DB::connection('mongodb') + return DB::connection('mongodb') ->collection('movies') ->where('year', 1955) ->orWhere('title', 'Back to the Future') ->get(); - // end query orWhere - - return $movies; } - private function runAndWhere() { + + private function runAndWhere() + { // begin query andWhere - $movies = DB::connection('mongodb') + return DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', '>', 8.5) ->where('year', '<', 1940) ->get(); - // end query andWhere - - return $movies; } - private function runNestedLogical() { + + private function runNestedLogical() + { // begin query nestedLogical - $movies = DB::connection('mongodb') + return DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', '>', 8.5) ->where(function ($query) { @@ -68,87 +76,71 @@ private function runNestedLogical() { ->where('year', 1986) ->orWhere('year', 1996); })->get(); - // end query nestedLogical - - return $movies; } - private function runWhereNot() { + + private function runWhereNot() + { // begin query whereNot - $movies = DB::connection('mongodb') + return DB::connection('mongodb') ->collection('movies') ->whereNot('imdb.rating', '>', 2) ->get(); - // end query whereNot - - return $movies; } - private function runWhereBetween() { + private function runWhereBetween() + { // begin query whereBetween - $movies = DB::connection('mongodb') + return DB::connection('mongodb') ->collection('movies') ->whereBetween('imdb.rating', [9, 9.5]) ->get(); - // end query whereBetween - - return $movies; } - private function runWhereNull() { + private function runWhereNull() + { // begin query whereNull - $movies = DB::connection('mongodb') + return DB::connection('mongodb') ->collection('movies') ->whereNull('runtime') ->get(); - // end query whereNull - - return $movies; } - private function runWhereDate() { + private function runWhereDate() + { // begin query whereDate - $movies = DB::connection('mongodb') + return DB::connection('mongodb') ->collection('movies') ->whereDate('released', '2010-1-15') ->get(); - // end query whereDate - - return $movies; } - private function runRegex() { + private function runRegex() + { // begin query whereRegex - $movies = DB::connection('mongodb') + return DB::connection('mongodb') ->collection('movies') - ->where('title', 'REGEX', new Regex('^the lord of .*', 'i' )) + ->where('title', 'REGEX', new Regex('^the lord of .*', 'i')) ->get(); - // end query whereRegex - - return $movies; } - - private function runWhereIn() { + private function runWhereIn() + { // begin query whereIn - $movies = DB::collection('movies') + return DB::collection('movies') ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) ->get(); - // end query whereIn - - return $movies; } - private function runLike() { + private function runLike() + { // begin query like - $movies = DB::collection('movies') + return DB::collection('movies') ->where('title', 'like', '%spider%man%') ->get(); - // end query like - - return $movies; } - private function runExists() { + private function runExists() + { // begin query exists $result = DB::collection('movies') ->exists('random_review', true); @@ -158,19 +150,16 @@ private function runExists() { return null; } - - private function runAll() { + private function runAll() + { // begin query all - $movies = DB::collection('movies') - ->where('movies', 'all', ['title', 'rated', 'imdb.rating' ]) + return DB::collection('movies') + ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) ->getl(); - // end query all - - return $movies; } - - private function runSize() { + private function runSize() + { // begin query size $result = DB::collection('movies') ->where('directors', 'size', 5) @@ -181,28 +170,24 @@ private function runSize() { return null; } - private function runType() { + private function runType() + { // begin query type - $movies = DB::collection('movies') + return DB::collection('movies') ->where('released', 'type', 4) ->get(); - // end query type - - return $movies; } - - private function runMod() { + private function runMod() + { // begin query modulo - $movies = DB::collection('movies') + return DB::collection('movies') ->where('year', 'mod', [2, 0]) ->get(); - // end query modulo - - return $movies; } - private function runDistinct() { + private function runDistinct() + { // begin query distinct $result = DB::collection('movies') ->distinct('year')->get(); @@ -211,7 +196,8 @@ private function runDistinct() { return null; } - private function runWhereDistinct() { + private function runWhereDistinct() + { // begin query where distinct $result = DB::collection('movies') ->where('imdb.rating', '>', 9) @@ -220,349 +206,346 @@ private function runWhereDistinct() { // end query where distinct print_r($result); return null; - } + } - private function runOrderBy() { + private function runOrderBy() + { // begin query orderBy - $movies = DB::collection('movies') - ->where('title', 'like', 'back to the future%') - ->orderBy('imdb.rating', 'desc') - ->get(); - // end query orderBy - - return $movies; - } + return DB::collection('movies') + ->where('title', 'like', 'back to the future%') + ->orderBy('imdb.rating', 'desc') + ->get(); + } - private function runGroupBy() { - // begin query groupBy + private function runGroupBy() + { + // begin query groupBy $result = DB::collection('movies') - ->groupBy('year') - ->get(['title']); + ->groupBy('year') + ->get(['title']); // end query groupBy print_r($result); return null; - } + } - private function runAggCount() { + private function runAggCount() + { // begin aggregation count - $result = DB::collection('movies') - ->count(); + $result = DB::collection('movies') + ->count(); // end aggregation count - print_r($result); - return null; + print_r($result); + return null; } - private function runAggMax() { + private function runAggMax() + { // begin aggregation max - $result = DB::collection('movies') - ->max('runtime'); + $result = DB::collection('movies') + ->max('runtime'); // end aggregation max - print_r($result); - return null; + print_r($result); + return null; } - private function runAggMin() { + private function runAggMin() + { // begin aggregation min - $result = DB::collection('movies') - ->min('year'); + $result = DB::collection('movies') + ->min('year'); // end aggregation min - print_r($result); - return null; + print_r($result); + return null; } - private function runAggAvg() { + private function runAggAvg() + { // begin aggregation avg - $result = DB::collection('movies') - ->avg('imdb.rating'); + $result = DB::collection('movies') + ->avg('imdb.rating'); // end aggregation avg - print_r($result); - return null; + print_r($result); + return null; } - private function runAggSum() { + private function runAggSum() + { // begin aggregation sum - $result = DB::collection('movies') - ->sum('imdb.votes'); + $result = DB::collection('movies') + ->sum('imdb.votes'); // end aggregation sum - print_r($result); - return null; + print_r($result); + return null; } - private function runAggWithFilter() { + private function runAggWithFilter() + { // begin aggregation with filter - $result = DB::collection('movies') - ->where('year', '>', 2000) - ->avg('imdb.rating'); + $result = DB::collection('movies') + ->where('year', '>', 2000) + ->avg('imdb.rating'); // end aggregation with filter - print_r($result); - return null; + print_r($result); + return null; } - private function runSkip() { + private function runSkip() + { // begin query skip - $movies = DB::collection('movies') - ->where('title', 'like', 'star trek%') - ->orderBy('year', 'asc') - ->skip(4) - ->get(); - // end query skip - - return $movies; - } - + return DB::collection('movies') + ->where('title', 'like', 'star trek%') + ->orderBy('year', 'asc') + ->skip(4) + ->get(); + } - private function runWhereRaw() { + private function runWhereRaw() + { // begin query raw - $movies = DB::collection('movies') - ->whereRaw([ - 'imdb.votes' => ['$gte' => 1000 ], - '$or' => [ - ['imdb.rating' => ['$gt' => 7]], - ['directors' => ['$in' => [ 'Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini' ]]] - ] - ]) - ->get(); - // end query raw - - return $movies; - } + return DB::collection('movies') + ->whereRaw([ + 'imdb.votes' => ['$gte' => 1000 ], + '$or' => [ + ['imdb.rating' => ['$gt' => 7]], + ['directors' => ['$in' => [ 'Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini' ]]], + ], + ]) + ->get(); + } - private function runElemMatch() { + private function runElemMatch() + { // begin query elemMatch - $movies = DB::collection('movies') - ->where('writers', 'elemMatch', ['$eq' => 'Lana Wilson', '$eq' => 'Maya Forbes']) - ->get(); - // end query elemMatch - - return $movies; - } - + return DB::collection('movies') + ->where('writers', 'elemMatch', ['$eq' => 'Lana Wilson', '$eq' => 'Maya Forbes']) + ->get(); + } - private function runNear() { + private function runNear() + { // begin query near $results = DB::collection('theaters') - ->where('location.geo', 'near', [ - '$geometry' => [ - 'type' => 'Point', - 'coordinates' => [ - -86.6423, 33.6054 - ], - ], - '$maxDistance' => 50, - ])->get(); + ->where('location.geo', 'near', [ + '$geometry' => [ + 'type' => 'Point', + 'coordinates' => [ + -86.6423, + 33.6054, + ], + ], + '$maxDistance' => 50, + ])->get(); // end query near print_r($results); return null; - } + } - private function runGeoWithin() { + private function runGeoWithin() + { // begin query geoWithin $results = DB::collection('theaters') - ->where('location.geo', 'geoWithin', [ - '$geometry' => [ - 'type' => 'Polygon', - 'coordinates' => [ - [ - [-72, 40], [-74, 41], [-72, 39], [-72, 40] - ], - ]]])->get(); + ->where('location.geo', 'geoWithin', [ + '$geometry' => [ + 'type' => 'Polygon', + 'coordinates' => [ + [ + [-72, 40], + [-74, 41], + [-72, 39], + [-72, 40], + ], + ], + ], + ])->get(); // end query geoWithin print_r($results); return null; - } - + } - private function runGeoIntersects() { + private function runGeoIntersects() + { // begin query geoIntersects $results = DB::collection('theaters') - ->where('location.geo', 'geoIntersects', [ - '$geometry' => [ - 'type' => 'LineString', - 'coordinates' => [ - [-73.600525, 40.74416], - [-72.600525, 40.74416], - ], - ], - ])->get(); + ->where('location.geo', 'geoIntersects', [ + '$geometry' => [ + 'type' => 'LineString', + 'coordinates' => [ + [-73.600525, 40.74416], + [-72.600525, 40.74416], + ], + ], + ])->get(); // end query geoIntersects print_r($results); return null; - } + } - private function runGeoNear() { + private function runGeoNear() + { // begin query geoNear - $results = DB::collection('theaters') - ->whereRaw([ - function($collection) { - return $collection->aggregate([ - [ - '$geoNear' => [ - 'near' => [ - 'type' => 'Point', - 'coordinates' => [ -118.34, 34.10 ], - ], - 'distanceField' => 'dist.calculated', - 'maxDistance' => 500, - 'includeLocs' => 'dist.location', - 'spherical' => true, - ] - ] - ]); - }])->get(); - // end query geoNear - print_r($results); - return null; - } - - private function runAggregate() { - $results = DB::collection('theaters') - ->whereRaw([ - function($collection) { + $results = DB::collection('theaters')->raw( + function (Collection $collection) { return $collection->aggregate([ - [ '$match' => [ 'theaterId', '>=', 8013] ]]); - - }])->get(); + [ + '$geoNear' => [ + 'near' => [ + 'type' => 'Point', + 'coordinates' => [-118.34, 34.10], + ], + 'distanceField' => 'dist.calculated', + 'maxDistance' => 500, + 'includeLocs' => 'dist.location', + 'spherical' => true, + ], + ], + ]); + }, + ); + // end query geoNear - print_r($results); + print_r($results->toArray()); return null; - } + } - private function runProjection() { + private function runProjection() + { // begin query projection $result = DB::collection('movies') - ->where('imdb.rating', '>', 8.5) - ->project([ - 'title' => 1, - 'cast' => ['$slice' => [1, 3]], - ]) - ->get(); + ->where('imdb.rating', '>', 8.5) + ->project([ + 'title' => 1, + 'cast' => ['$slice' => [1, 3]], + ]) + ->get(); // end query projection print_r($result->toJson()); return null; - } + } - private function runProjectionWithPagination() { + private function runProjectionWithPagination() + { // begin query projection with pagination $resultsPerPage = 15; $projectionFields = ['title', 'runtime', 'imdb.rating']; $result = DB::collection('movies') - ->orderBy('imdb.votes', 'desc') - ->paginate($resultsPerPage, $projectionFields); + ->orderBy('imdb.votes', 'desc') + ->paginate($resultsPerPage, $projectionFields); // end query projection with pagination print_r($result->toJson()); return null; - } + } - private function runCursorTimeout() { + private function runCursorTimeout() + { // begin query cursor timeout - $movies = DB::collection('movies') - ->timeout(2) // value in seconds - ->where('year', 2001) - ->get(); - // end query cursor timeout - - return $movies; - } + return DB::collection('movies') + ->timeout(2) // value in seconds + ->where('year', 2001) + ->get(); + } - private function runUpsert() { + private function runUpsert() + { // begin upsert - $movies = DB::collection('movies') - ->where('title', 'Will Hunting') - ->update([ - 'plot' => 'An autobiographical movie', - 'year' => 1998, - 'writers' => [ 'Will Hunting' ], - ], - ['upsert' => true]); - // end upsert - - return $movies; - } - - private function runIncrement() { + return DB::collection('movies') + ->where('title', 'Will Hunting') + ->update( + [ + 'plot' => 'An autobiographical movie', + 'year' => 1998, + 'writers' => [ 'Will Hunting' ], + ], + ['upsert' => true], + ); + } + + private function runIncrement() + { // begin increment $result = DB::collection('movies') - ->where('title', 'Field of Dreams') - ->increment('imdb.votes', 3000); + ->where('title', 'Field of Dreams') + ->increment('imdb.votes', 3000); // end increment print_r($result); return $result; - } + } - private function runDecrement() { + private function runDecrement() + { // begin decrement $result = DB::collection('movies') - ->where('title', 'Sharknado') - ->decrement('imdb.rating', 0.2); + ->where('title', 'Sharknado') + ->decrement('imdb.rating', 0.2); // end decrement print_r($result); return $result; - } - + } - private function runPush() { + private function runPush() + { // begin push $result = DB::collection('movies') - ->where('title', 'Office Space') - ->push('cast', 'Gary Cole'); + ->where('title', 'Office Space') + ->push('cast', 'Gary Cole'); // end push print_r($result); return $result; - } - + } - private function runPull() { + private function runPull() + { // begin pull $result = DB::collection('movies') - ->where('title', 'Iron Man') - ->pull('genres', 'Adventure'); + ->where('title', 'Iron Man') + ->pull('genres', 'Adventure'); // end pull print_r($result); return $result; - } + } - private function runUnset() { + private function runUnset() + { // begin unset $result = DB::collection('movies') - ->where('title', 'Final Accord') - ->unset('tomatoes.viewer'); + ->where('title', 'Final Accord') + ->unset('tomatoes.viewer'); // end unset print_r($result); return $result; - } + } /** * Display the specified resource. */ public function show() { - $result = null; - //$result = $this->runWhere(); + $result = $this->runWhere()->toJson(); + echo '{$result}'; //$result = $this->runOrWhere(); //$result = $this->runAndWhere(); - // $result = $this->runNestedLogical(); + //$result = $this->runNestedLogical(); //$result = $this->runWhereNot(); @@ -574,7 +557,7 @@ public function show() //$result = $this->runLike(); - $result = $this->runExists(); + //$result = $this->runExists(); //$result = $this->runAll(); @@ -597,7 +580,6 @@ public function show() //$result = $this->runGeoIntersects(); //$result = $this->runGeoNear(); - //TODO $result = $this->runAggregate(); //$result = $this->runWhereIn(); @@ -611,7 +593,7 @@ public function show() //$result = $this->runAggCount(); - //$result = $this->runAggMax(); + //$result = $this->runAggMax(); //$result = $this->runAggMin(); @@ -623,7 +605,7 @@ public function show() //$result = $this->runSkip(); - //$result = Movie::where('year', 1999)->get(); //first(); + //$result = Movie::where('year', 1999)->get(); //$result = $this->runProjection(); @@ -644,23 +626,27 @@ public function show() //$result = $this->runUnset(); //$result = Movie::first(); - return view('browse_movies', [ - 'movies' => $result - ]); + return view('browse_movies', ['movies' => $result]); } /** * Show the form for editing the specified resource. */ - public function edit(Movie $movie) {} + public function edit(Movie $movie) + { + } /** * Update the specified resource in storage. */ - public function update(Request $request, Movie $movie) {} + public function update(Request $request, Movie $movie) + { + } /** * Remove the specified resource from storage. */ - public function destroy(Movie $movie) {} + public function destroy(Movie $movie) + { + } } diff --git a/docs/query-builder.txt b/docs/query-builder.txt index bc3a9dbf1..2a712d9d0 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -66,8 +66,8 @@ To perform read and write operations by using the query builder, import the .. _laravel-retrieve-query-builder: -Retrieve Documents ------------------- +Retrieve Matching Documents +--------------------------- This section includes query builder examples for read operations in the following operator categories: @@ -99,29 +99,44 @@ by the query: :end-before: end query where .. output:: - :language: none + :language: json :visible: false - Title: Cosmos - Year: 1980 - Runtime: 60 - IMDB Rating: 9.3 - IMDB Votes: 17174 - Plot: Astronomer Carl Sagan leads us on an engaging guided tour of the various elements and cosmological theories of the universe. - - Title: The Shawshank Redemption - Year: 1994 - Runtime: 142 - IMDB Rating: 9.3 - IMDB Votes: 1521105 - Plot: Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency. - - Title: The Real Miyagi - Year: 2015 - Runtime: 90 - IMDB Rating: 9.3 - IMDB Votes: 41 - Plot: The life of the greatest karate master of a generation. + [ + { "title": "Cosmos", + "year": 1980, + "runtime": 60, + "imdb": { + "rating": 9.3, + "votes": 17174, + "id": 81846 + }, + "plot": "Astronomer Carl Sagan leads us on an engaging guided tour of the various elements and cosmological theories of the universe.", + ... + }, + { "title": "The Shawshank Redemption", + "year": 1994, + "runtime": 142, + "imdb": { + "rating": 9.3, + "votes": 1521105, + "id": 111161 + }, + "plot": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", + ... + }, + { "title": "The Real Miyagi", + "year": 2015, + "runtime": 90, + "imdb": { + "rating": 9.3, + "votes": 41, + "id": 2313306 + }, + "plot": "The life of the greatest karate master of a generation.", + ... + } + ] .. _laravel-query-builder-logical-operations: @@ -370,17 +385,15 @@ query builder method to retrieve documents from the :end-before: end query like .. output:: - :language: none + :language: json :visible: false - Title: Kiss of the Spider Woman - ... - - Title: Spider-Man - ... - - Title: Spider-Man 2 - ... + [ + { "title": "Kiss of the Spider Woman", ... }, + { "title": "Spider-Man", ... }, + { "title": "Spider-Man 2", ...}, + ... + ] .. _laravel-query-builder-distinct: From e2f34d6a32db3c56d607a4cfba80e82f94cf569c Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 22 Mar 2024 17:57:53 -0400 Subject: [PATCH 19/36] reformat code --- .../query-builder/MovieController.php | 138 ++++++++++++++---- 1 file changed, 108 insertions(+), 30 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index ec194ce8a..2df2a8a90 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -39,36 +39,48 @@ public function store(Request $request) private function runWhere() { // begin query where - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', 9.3) ->get(); + // end query where + + echo "{$result->toJson()}"; + return $result; } private function runOrWhere() { // begin query orWhere - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->where('year', 1955) ->orWhere('title', 'Back to the Future') ->get(); + // end query orWhere + + echo "{$result->toJson()}"; + return $result; } private function runAndWhere() { // begin query andWhere - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', '>', 8.5) ->where('year', '<', 1940) ->get(); + // end query andWhere + + echo "{$result->toJson()}"; + return $result; } private function runNestedLogical() { // begin query nestedLogical - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', '>', 8.5) ->where(function ($query) { @@ -76,67 +88,99 @@ private function runNestedLogical() ->where('year', 1986) ->orWhere('year', 1996); })->get(); + // end query nestedLogical + + echo "{$result->toJson()}"; + return $result; } private function runWhereNot() { // begin query whereNot - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->whereNot('imdb.rating', '>', 2) ->get(); + // end query whereNot + + echo "{$result->toJson()}"; + return $result; } private function runWhereBetween() { // begin query whereBetween - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->whereBetween('imdb.rating', [9, 9.5]) ->get(); + // end query whereBetween + + echo "{$result->toJson()}"; + return $result; } private function runWhereNull() { // begin query whereNull - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->whereNull('runtime') ->get(); + // end query whereNull + + echo "{$result->toJson()}"; + return $result; } private function runWhereDate() { // begin query whereDate - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->whereDate('released', '2010-1-15') ->get(); + // end query whereDate + + echo "{$result->toJson()}"; + return $result; } private function runRegex() { // begin query whereRegex - return DB::connection('mongodb') + $result = DB::connection('mongodb') ->collection('movies') ->where('title', 'REGEX', new Regex('^the lord of .*', 'i')) ->get(); + // end query whereRegex + + echo "{$result->toJson()}"; + return $result; } private function runWhereIn() { // begin query whereIn - return DB::collection('movies') + $result = DB::collection('movies') ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) ->get(); + // end query whereIn + + echo "{$result->toJson()}"; + return $result; } private function runLike() { // begin query like - return DB::collection('movies') + $result = DB::collection('movies') ->where('title', 'like', '%spider%man%') ->get(); + // end query like + + echo "{$result->toJson()}"; + return $result; } private function runExists() @@ -153,9 +197,13 @@ private function runExists() private function runAll() { // begin query all - return DB::collection('movies') + $result = DB::collection('movies') ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) ->getl(); + // end query all + + echo "{$result->toJson()}"; + return $result; } private function runSize() @@ -173,17 +221,25 @@ private function runSize() private function runType() { // begin query type - return DB::collection('movies') + $result = DB::collection('movies') ->where('released', 'type', 4) ->get(); + // end query type + + echo "{$result->toJson()}"; + return $result; } private function runMod() { // begin query modulo - return DB::collection('movies') + $result = DB::collection('movies') ->where('year', 'mod', [2, 0]) ->get(); + // end query modulo + + echo "{$result->toJson()}"; + return $result; } private function runDistinct() @@ -211,10 +267,14 @@ private function runWhereDistinct() private function runOrderBy() { // begin query orderBy - return DB::collection('movies') + $result = DB::collection('movies') ->where('title', 'like', 'back to the future%') ->orderBy('imdb.rating', 'desc') ->get(); + // end query orderBy + + echo "{$result->toJson()}"; + return $result; } private function runGroupBy() @@ -299,33 +359,44 @@ private function runAggWithFilter() private function runSkip() { // begin query skip - return DB::collection('movies') + $result = DB::collection('movies') ->where('title', 'like', 'star trek%') ->orderBy('year', 'asc') ->skip(4) ->get(); + // end query skip + + echo "{$result->toJson()}"; + return $result; } private function runWhereRaw() { // begin query raw - return DB::collection('movies') - ->whereRaw([ - 'imdb.votes' => ['$gte' => 1000 ], - '$or' => [ - ['imdb.rating' => ['$gt' => 7]], - ['directors' => ['$in' => [ 'Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini' ]]], - ], - ]) - ->get(); + $result = DB::collection('movies') + ->whereRaw([ + 'imdb.votes' => ['$gte' => 1000 ], + '$or' => [ + ['imdb.rating' => ['$gt' => 7]], + ['directors' => ['$in' => [ 'Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini' ]]], + ], + ])->get(); + // end query raw + + echo "{$result->toJson()}"; + return $result; } private function runElemMatch() { // begin query elemMatch - return DB::collection('movies') + $result = DB::collection('movies') ->where('writers', 'elemMatch', ['$eq' => 'Lana Wilson', '$eq' => 'Maya Forbes']) ->get(); + // end query elemMatch + + echo "{$result->toJson()}"; + return $result; } private function runNear() @@ -451,16 +522,20 @@ private function runProjectionWithPagination() private function runCursorTimeout() { // begin query cursor timeout - return DB::collection('movies') + $result = DB::collection('movies') ->timeout(2) // value in seconds ->where('year', 2001) ->get(); + // end query cursor timeout + + echo "{$result->toJson()}"; + return $result; } private function runUpsert() { // begin upsert - return DB::collection('movies') + $result = DB::collection('movies') ->where('title', 'Will Hunting') ->update( [ @@ -470,6 +545,10 @@ private function runUpsert() ], ['upsert' => true], ); + // end upsert + + echo "{$result->toJson()}"; + return $result; } private function runIncrement() @@ -538,8 +617,7 @@ private function runUnset() public function show() { $result = null; - $result = $this->runWhere()->toJson(); - echo '{$result}'; + $result = $this->runWhere(); //$result = $this->runOrWhere(); From 3775d5a65c394de95eb9759a7ad23caed4ddd5bd Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Sat, 23 Mar 2024 02:30:26 -0400 Subject: [PATCH 20/36] WIP --- .../query-builder/MovieController.php | 46 +----- docs/query-builder.txt | 144 ++++++------------ 2 files changed, 50 insertions(+), 140 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index 2df2a8a90..b7bf1ad21 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -391,7 +391,7 @@ private function runElemMatch() { // begin query elemMatch $result = DB::collection('movies') - ->where('writers', 'elemMatch', ['$eq' => 'Lana Wilson', '$eq' => 'Maya Forbes']) + ->where('writers', 'elemMatch', ['$in' => ['Maya Forbes', 'Eric Roth']]) ->get(); // end query elemMatch @@ -617,90 +617,48 @@ private function runUnset() public function show() { $result = null; - $result = $this->runWhere(); - + //$result = $this->runWhere(); //$result = $this->runOrWhere(); - //$result = $this->runAndWhere(); - //$result = $this->runNestedLogical(); - //$result = $this->runWhereNot(); - //$result = $this->runWhereBetween(); - //$result = $this->runWhereNull(); - //$result = $this->runWhereDate(); - //$result = $this->runLike(); - //$result = $this->runExists(); - //$result = $this->runAll(); - //$result = $this->runSize(); - //$result = $this->runType(); - //$result = $this->runMod(); - //$result = $this->runRegex(); - //$result = $this->runWhereRaw(); - //$result = $this->runElemMatch(); - //$result = $this->runNear(); - //$result = $this->runGeoWithin(); - //$result = $this->runGeoIntersects(); - //$result = $this->runGeoNear(); - //$result = $this->runWhereIn(); - //$result = $this->runDistinct(); - //$result = $this->runWhereDistinct(); - //$result = $this->runOrderBy(); - //$result = $this->runGroupBy(); - //$result = $this->runAggCount(); - //$result = $this->runAggMax(); - //$result = $this->runAggMin(); - //$result = $this->runAggAvg(); - //$result = $this->runAggSum(); - //$result = $this->runAggWithFilter(); - //$result = $this->runSkip(); - //$result = Movie::where('year', 1999)->get(); - //$result = $this->runProjection(); - //$result = $this->runProjectionWithPagination(); - //$result = $this->runCursorTimeout(); - //$result = $this->runUpsert(); - //$result = $this->runIncrement(); - //$result = $this->runDecrement(); - //$result = $this->runPush(); - //$result = $this->runPull(); - //$result = $this->runUnset(); //$result = Movie::first(); diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 2a712d9d0..60ceef9ed 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -59,7 +59,8 @@ Before You Get Started To run the code examples in this guide, complete the :ref:`Quick Start ` tutorial to configure a web -application and run the example code from a controller method. +application, load sample datasets into your MongoDB deployment, and +run the example code from a controller method. To perform read and write operations by using the query builder, import the ``Illuminate\Support\Facades\DB`` facade and compose your query. @@ -245,24 +246,15 @@ between "9" and "9.5": :end-before: end query whereBetween .. output:: - :language: none + :language: json :visible: false - Title: Hollywood - Year: 1980 - Runtime: 60 - IMDB Rating: 9.1 - IMDB Votes: 511 - Plot: The definitive documentary about the American silent film industry. - - Title: Cosmos - Year: 1980 - Runtime: 60 - IMDB Rating: 9.3 - IMDB Votes: 17174 - Plot: Astronomer Carl Sagan leads us on an engaging guided tour of the various elements and cosmological theories of the universe. - - ... + [ + { "title" "The Godfather", "imdb": { "rating": 9.2, "votes": 1038358, "id": 68646 }, ... }, + { "title": "Hollywood", "imdb": { "rating": 9.1, "votes": 511,"id": 80230 }, ... }, + { "title": "Cosmos", "imdb": { "rating": 9.3, "votes": 17174, "id": 81846 }, ... }, + ... + ] .. _laravel-query-builder-empty-null: @@ -274,31 +266,11 @@ query builder method to retrieve documents from the ``movies`` collection that omit a ``runtime`` value or field. -.. io-code-block:: - - .. input:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query whereNull - :end-before: end query whereNull - - .. output:: - :language: none - :visible: false - - Title: The Secret of the Magic Gourd - Year: 2007 - Runtime: - IMDB Rating: 5.6 - IMDB Votes: 340 - Plot: A boy learns the meaning of work after a magic gourd grants him anything he wants. - - Title: Jekyll - Year: 2007 - Runtime: - IMDB Rating: 8.2 - IMDB Votes: 6248 - Plot: London, 2007. Tom Jackman is the only living descendent of Dr. Jekyll and Mr. Hyde. He has made a deal with his dark side: a body share. What Mr. Hyde doesn't know is that Tom has a family.... +.. literalinclude:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query whereNull + :end-before: end query whereNull .. seealso:: @@ -323,29 +295,15 @@ query builder method to retrieve documents from the :end-before: end query whereIn .. output:: - :language: none + :language: json :visible: false - Title: Toy Story - Year: 1995 - Runtime: 81 - IMDB Rating: 8.3 - IMDB Votes: 542659 - Plot: A cowboy doll is profoundly threatened and jealous when a new spaceman figure supplants him as top toy in a boy's room. - - Title: Johnny English - Year: 2003 - Runtime: 87 - IMDB Rating: 6.1 - IMDB Votes: 107074 - Plot: After a sudden attack on the MI5, Johnny English, Britain's most confident yet unintelligent spy, becomes Britain's only spy. - - Title: Shrek 2 - Year: 2004 - Runtime: 93 - IMDB Rating: 7.2 - IMDB Votes: 283852 - Plot: Princess Fiona's parents invite her and Shrek to dinner to celebrate her marriage. If only they knew the newlyweds were both ogres. + [ + { "title": "Toy Story", "year": 1995, "runtime": 81, ... }, + { "title": "Johnny English", "year": 2003, "runtime": 87, ... }, + { "title": "Shrek 2", "year" 2004, "runtime": 93, ... }, + ... + ] .. _laravel-query-builder-wheredate: @@ -419,13 +377,13 @@ The examples in this section show the query builder syntax you can use to perform aggregations, a set of calculations on the query results, to return the following information: -- Results Grouped by Common Field Values -- Number of Results -- Maximum Value of a Field -- Minimum Value of a Field -- Average Value of a Field -- Summed Value of a Field -- Aggregation on Matched Results +- :ref:`Results Grouped by Common Field Values ` +- :ref:`Number of Results ` +- :ref:`Maximum Value of a Field ` +- :ref:`Minimum Value of a Field ` +- :ref:`Average Value of a Field ` +- :ref:`Summed Value of a Field ` +- :ref:`Aggregate Matched Results ` .. _laravel-query-builder-aggregation-groupby: @@ -523,10 +481,10 @@ collection: :start-after: begin aggregation sum :end-before: end aggregation sum -.. _laravel-query-builder-aggregation-filter: +.. _laravel-query-builder-aggregate-matched: -Aggregation on Matched Results Example -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Aggregate Matched Results Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The following example shows how to use the ``sum()`` query builder method to return the numerical total of @@ -541,8 +499,8 @@ after the year "2000": .. _laravel-modify-results-query-builder: -Modify Results --------------- +Modify Query Results +-------------------- This section includes query builder examples for the following functions that modify the order and format @@ -572,20 +530,15 @@ the filter specified in the ``title`` field by the :end-before: end query orderBy .. output:: - :language: none + :language: json :visible: false - Title: Back to the Future - IMDB Rating: 8.5 - ... - - Title: Back to the Future Part II - IMDB Rating: 7.8 - ... - - Title: Back to the Future Part III - IMDB Rating: 7.4 - ... + [ + { "title": "Back to the Future", "imdb": { "rating":8.5,"votes":636511,"id":88763 }, ... }, + { "title": "Back to the Future Part II", "imdb": { "rating":7.8,"votes":292539,"id":96874 }, ... }, + { "title": "Back to the Future Part III", "imdb": {"rating":7.4,"votes":242390,"id":99088 }, ... }, + ... + ] .. _laravel-query-builder-skip: @@ -610,13 +563,12 @@ Show a Subset of Fields and Array Values in the Results Example The following example shows how to use the ``project()`` query builder method to match documents that contain an -``imdb.rating`` value higher than "8.5" and return results -that only the following field values: - -- ``title`` field -- ``cast`` field, including only the second through the fourth values of the array if they exist -- ``_id`` field, which is automatically included +``imdb.rating`` value higher than "8.5" and return +only the following field values: +- Title of the movie in the ``title`` +- Second through fourth values of the ``cast`` array field, if they exist +- Document ``_id`` field, which is automatically included .. io-code-block:: @@ -857,9 +809,9 @@ Match Array Elements Example The following example shows how to pass the ``elemMatch`` query operator with the ``where()`` query builder -method to match documents that contain a at least one -array element that matches at least one of the conditions -in the specified query: +method to match documents that contain an array element +that matches at least one of the conditions in the +specified query: .. literalinclude:: /includes/query-builder/MovieController.php :language: php From 13089273a907833b8e39d6746a04f553f58a768b Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Sun, 24 Mar 2024 12:22:31 -0400 Subject: [PATCH 21/36] elemmatch update --- .../query-builder/MovieController.php | 9 +- docs/query-builder.txt | 103 ++++++++++++++---- 2 files changed, 87 insertions(+), 25 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index b7bf1ad21..c0a52beb7 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -281,10 +281,13 @@ private function runGroupBy() { // begin query groupBy $result = DB::collection('movies') - ->groupBy('year') - ->get(['title']); + ->where('rated', 'G') + ->groupBy('runtime') + ->orderBy('runtime', 'asc') + ->get(['title']); // end query groupBy + $result = $result->toJson(); print_r($result); return null; } @@ -633,7 +636,7 @@ public function show() //$result = $this->runMod(); //$result = $this->runRegex(); //$result = $this->runWhereRaw(); - //$result = $this->runElemMatch(); + //result = $this->runElemMatch(); //$result = $this->runNear(); //$result = $this->runGeoWithin(); //$result = $this->runGeoIntersects(); diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 60ceef9ed..2fc1f51e0 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -92,6 +92,7 @@ that contain a ``imdb.votes`` field value of ``350``. Click the by the query: .. io-code-block:: + :copyable: true .. input:: /includes/query-builder/MovieController.php :language: php @@ -141,16 +142,18 @@ by the query: .. _laravel-query-builder-logical-operations: -Logical Conditional Operation Examples -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Logical Conditional Operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The examples in this section show the query builder syntax you can use to perform the following logical conditional operations: -- **OR** by chaining the ``orWhere()`` function -- **AND** by chaining another ``where()`` function -- **NOT** which uses the ``whereNot()`` function -- Nested logical operator groups +- :ref:`Logical OR to match one or more conditions ` +- :ref:`Logical AND to match all conditions ` +- :ref:`Logical NOT which matches the negation of the condition ` +- :ref:`Nested logical operator groups ` + +.. _laravel-query-builder-logical-or: Logical OR Example ^^^^^^^^^^^^^^^^^^ @@ -166,6 +169,8 @@ value of "1955" or match the title "Back to the Future": :start-after: begin query orWhere :end-before: end query orWhere +.. _laravel-query-builder-logical-and: + Logical AND Example ^^^^^^^^^^^^^^^^^^^ @@ -181,6 +186,8 @@ value greater than "8.5" and a ``year`` value of less than :start-after: begin query andWhere :end-before: end query andWhere +.. _laravel-query-builder-logical-not: + Logical NOT Example ^^^^^^^^^^^^^^^^^^^ @@ -196,6 +203,8 @@ value greater than "8.5" and a ``year`` value of less than :start-after: begin query whereNot :end-before: end query whereNot +.. _laravel-query-builder-logical-nested: + Nested Logical Operator Group Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -222,10 +231,10 @@ The examples in this section show the query builder syntax you can use to perform to match values by using the following range queries and type check operations: -- Values within a numerical range -- Empty or null values -- One or more values of a set -- Dates +- :ref:`Values within a numerical range ` +- :ref:`Null or missing values ` +- :ref:`One or more values of a set ` +- :ref:`Match dates ` .. _laravel-query-builder-wherebetween: @@ -238,6 +247,7 @@ query builder method to retrieve documents from the between "9" and "9.5": .. io-code-block:: + :copyable: true .. input:: /includes/query-builder/MovieController.php :language: php @@ -256,10 +266,10 @@ between "9" and "9.5": ... ] -.. _laravel-query-builder-empty-null: +.. _laravel-query-builder-null: -Empty or Null Value Example -^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Null or Missing Values Example +^^^^^^^^^^^^^^^^^^^^^^^^^^^%^^ The following example shows how to use the ``whereNull()`` query builder method to retrieve documents from the @@ -287,6 +297,7 @@ query builder method to retrieve documents from the ``title`` values in the specified set. .. io-code-block:: + :copyable: true .. input:: /includes/query-builder/MovieController.php :language: php @@ -307,8 +318,8 @@ query builder method to retrieve documents from the .. _laravel-query-builder-wheredate: -Dates Example -^^^^^^^^^^^^^ +Match Dates Example +^^^^^^^^^^^^^^^^^^^ The following example shows how to use the ``whereDate()`` query builder method to retrieve documents from the @@ -335,6 +346,7 @@ query builder method to retrieve documents from the ``movies`` collection that match the specified pattern: .. io-code-block:: + :copyable: true .. input:: /includes/query-builder/MovieController.php :language: php @@ -391,14 +403,59 @@ Results Grouped by Common Field Values Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The following example shows how to use the ``groupBy()`` -query builder method to retrieve documents as -TODO: fix this +query builder method to retrieve document data, grouped +by common values of the ``runtime`` field. This example +chains the following operations to match documents from +the ``movies`` collection that contain a ``rated`` +value of ``G`` and include the ``title`` field of one +movie for each distinct ``runtime`` value: + +- Match only documents that contain a ``rated`` field value of "G" by + using the ``where()`` method +- Group data by the distinct values of the ``runtime`` field, which is + assigned the ``_id`` field, by using the ``groupBy()`` method +- Sort the groups by the ``runtime`` field by using the ``orderBy()`` method +- Return ``title`` data from the last document in the grouped result by + specifying it in the ``get()`` method + +.. tip:: + + The ``groupBy()`` method calls the MongoDB ``$group`` aggregation operator + and ``$last`` accumulator operator. To learn more about these, see + :manual:`$group (aggregation) ` + in the {+server-docs-name+}. -.. literalinclude:: /includes/query-builder/MovieController.php - :language: php - :dedent: - :start-after: begin query groupBy - :end-before: end query groupBy +.. io-code-block:: + :copyable: true + + .. input:: /includes/query-builder/MovieController.php + :language: php + :dedent: + :start-after: begin query groupBy + :end-before: end query groupBy + + .. output:: + :language: json + :visible: false + + [ + ... + { + "_id": { + "runtime": 64 + }, + "runtime": 64, + "title": "Stitch! The Movie" + }, + { + "_id": { + "runtime": 67 + }, + "runtime": 67, + "title": "Bartok the Magnificent" + }, + ... + ] .. _laravel-query-builder-aggregation-count: @@ -522,6 +579,7 @@ the filter specified in the ``title`` field by the ``imdb.rating`` value in descending order: .. io-code-block:: + :copyable: true .. input:: /includes/query-builder/MovieController.php :language: php @@ -571,6 +629,7 @@ only the following field values: - Document ``_id`` field, which is automatically included .. io-code-block:: + :copyable: true .. input:: /includes/query-builder/MovieController.php :language: php From 94b00d66d453dedaa6f7167417eb3ca3210e8a16 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Sun, 24 Mar 2024 14:22:34 -0400 Subject: [PATCH 22/36] fixes --- docs/query-builder.txt | 151 ++++++++++++++++++++--------------------- 1 file changed, 75 insertions(+), 76 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 2fc1f51e0..144559f1a 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -27,19 +27,19 @@ interface and syntax. .. note:: - {+odm-short+} extends Laravel's query builder and Eloquent ORM, both of - which can run similar database operations. To learn more about retrieving - documents by using Eloquent models, see :ref:`laravel-fundamentals-retrieve`. + {+odm-short+} extends Laravel's query builder and Eloquent ORM, which can + run similar database operations. To learn more about retrieving documents + by using Eloquent models, see :ref:`laravel-fundamentals-retrieve`. Laravel provides a **facade** to access the query builder class ``DB``, which lets you perform database operations. Facades are static interfaces to -classes that make the syntax more concise, avoid runtime errors,and improve +classes that make the syntax more concise, avoid runtime errors, and improve testability. -{+odm-short+} aliases the ``DB`` method ``table()`` as ``collection()``. Chain -methods to specify the command and any constraints. Then, chain the ``get()`` -method at the end to run them on the MongoDB collection. The following example -shows the syntax of a query builder call: +{+odm-short+} aliases the ``DB`` method ``table()`` as the ``collection()`` +method. Chain methods to specify the command and any constraints. Then, chain +the ``get()`` method at the end to run them on the MongoDB collection. The +following example shows the syntax of a query builder call: .. code-block:: php @@ -87,7 +87,7 @@ Where Method Example The following example shows how to use the ``where()`` query builder method to retrieve documents from the ``movies`` collection -that contain a ``imdb.votes`` field value of ``350``. Click the +that contain an ``imdb.votes`` field value of ``350``. Click the :guilabel:`{+code-output-label+}` button to see the results returned by the query: @@ -149,9 +149,9 @@ The examples in this section show the query builder syntax you can use to perform the following logical conditional operations: - :ref:`Logical OR to match one or more conditions ` -- :ref:`Logical AND to match all conditions ` -- :ref:`Logical NOT which matches the negation of the condition ` -- :ref:`Nested logical operator groups ` +- :ref:`Logical AND to match all conditions ` +- :ref:`Logical NOT to match the negation of the condition ` +- :ref:`Nested logical operator groups ` .. _laravel-query-builder-logical-or: @@ -235,6 +235,7 @@ queries and type check operations: - :ref:`Null or missing values ` - :ref:`One or more values of a set ` - :ref:`Match dates ` +- :ref:`Match a text pattern ` .. _laravel-query-builder-wherebetween: @@ -269,7 +270,7 @@ between "9" and "9.5": .. _laravel-query-builder-null: Null or Missing Values Example -^^^^^^^^^^^^^^^^^^^^^^^^^^^%^^ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The following example shows how to use the ``whereNull()`` query builder method to retrieve documents from the @@ -334,16 +335,18 @@ query builder method to retrieve documents from the .. _laravel-query-builder-pattern: -Pattern Search Example -~~~~~~~~~~~~~~~~~~~~~~ - -To specify a pattern, use the ``%`` symbol to match -zero or more characters or the ``_`` symbol to match -any single character. +Text Pattern Match Example +~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``like()`` query builder method to retrieve documents from the -``movies`` collection that match the specified pattern: +``movies`` collection by using a specified text pattern. + +Text patterns can contain text mixed with the following +wildcard characters: + +- ``%`` which matches zero or more characters +- ``_`` which matches a single character .. io-code-block:: :copyable: true @@ -389,26 +392,24 @@ The examples in this section show the query builder syntax you can use to perform aggregations, a set of calculations on the query results, to return the following information: -- :ref:`Results Grouped by Common Field Values ` -- :ref:`Number of Results ` -- :ref:`Maximum Value of a Field ` -- :ref:`Minimum Value of a Field ` -- :ref:`Average Value of a Field ` -- :ref:`Summed Value of a Field ` -- :ref:`Aggregate Matched Results ` +- :ref:`Results grouped by common field values ` +- :ref:`Count the of results ` +- :ref:`Maximum value of a field ` +- :ref:`Minimum value of a field ` +- :ref:`Average value of a field ` +- :ref:`Summed value of a field ` +- :ref:`Aggregate matched results ` .. _laravel-query-builder-aggregation-groupby: Results Grouped by Common Field Values Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The following example shows how to use the ``groupBy()`` -query builder method to retrieve document data, grouped -by common values of the ``runtime`` field. This example -chains the following operations to match documents from -the ``movies`` collection that contain a ``rated`` -value of ``G`` and include the ``title`` field of one -movie for each distinct ``runtime`` value: +The following example shows how to use the ``groupBy()`` query builder method +to retrieve document data grouped by shared values of the ``runtime`` field. +This example chains the following operations to match documents from the +``movies`` collection that contain a ``rated`` value of ``G`` and include the +``title`` field of one movie for each distinct ``runtime`` value: - Match only documents that contain a ``rated`` field value of "G" by using the ``where()`` method @@ -421,7 +422,7 @@ movie for each distinct ``runtime`` value: .. tip:: The ``groupBy()`` method calls the MongoDB ``$group`` aggregation operator - and ``$last`` accumulator operator. To learn more about these, see + and ``$last`` accumulator operator. To learn more about these operators, see :manual:`$group (aggregation) ` in the {+server-docs-name+}. @@ -429,7 +430,7 @@ movie for each distinct ``runtime`` value: :copyable: true .. input:: /includes/query-builder/MovieController.php - :language: php + :language: php :dedent: :start-after: begin query groupBy :end-before: end query groupBy @@ -441,19 +442,20 @@ movie for each distinct ``runtime`` value: [ ... { - "_id": { - "runtime": 64 - }, + "_id": { "runtime": 64 }, "runtime": 64, "title": "Stitch! The Movie" }, { - "_id": { - "runtime": 67 - }, + "_id": { "runtime": 67 }, "runtime": 67, "title": "Bartok the Magnificent" }, + { + "_id": { "runtime":68 }, + "runtime": 68, + "title": "Mickey's Twice Upon a Christmas" + }, ... ] @@ -463,9 +465,8 @@ Number of Results Example ^^^^^^^^^^^^^^^^^^^^^^^^^ The following example shows how to use the ``count()`` -query builder method to return the number of results -from a query that matches the entire ``movies`` -collection: +query builder method to return the number of documents +contained in the ``movies`` collection: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -603,10 +604,9 @@ the filter specified in the ``title`` field by the Omit a Specified Number of Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``skip()`` -query builder method to omit the first "4" results that -match the filter speficied in the ``title`` field, -sorted by the ``year`` value in descending order: +The following example shows how to use the ``skip()`` query builder method to +omit the first "4" results that match the filter specified in the ``title`` +field, sorted by the ``year`` value in descending order: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -677,13 +677,11 @@ only the following field values: Paginate the Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``paginate()`` -query builder method to divide the entire ``movie`` -collection into discrete result sets of 15 documents. -The example also includes a sort order to arrange the -results by the ``imdb.votes`` field in descending order -and a projection to include only specific fields in -the results. +The following example shows how to use the ``paginate()`` query builder method +to divide the entire ``movie`` collection into discrete result sets of 15 +documents. The example also includes a sort order to arrange the results by +the ``imdb.votes`` field in descending order and a projection that includes +only specific fields in the results. .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -700,20 +698,19 @@ in the Laravel documentation. MongoDB Read Operations ----------------------- -This section includes query builder examples that -show how to use the following MongoDB-specific query -operations: +This section includes query builder examples that show how +to use the following MongoDB-specific query operations: -- :ref:`Match documetns that contain a field ` +- :ref:`Match documents that contain a field ` - :ref:`Match documents that contain all specified fields ` - :ref:`Match documents that contain a specific number of elements in an array ` -- :ref:`Match documents that contain a specific data type in a field ` +- :ref:`Match documents that contain a particular data type in a field ` - :ref:`Match documents that contain a computed modulo value ` - :ref:`Match documents that match a regular expression ` -- :ref:`Run MongoDB Query API queries ` +- :ref:`Run MongoDB operations ` - :ref:`Match documents that contain array elements ` - :ref:`Specify a cursor timeout ` -- :ref:`Match Locations by Using Geospatial Operations ` +- :ref:`Match locations by using geospatial searches ` .. _laravel-query-builder-exists: @@ -739,10 +736,9 @@ in the {+server-docs-name+}. Contains All Fields Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``all`` -query operator with the ``where()`` query builder -method to match documents that contain all the -specified fields: +The following example shows how to use the ``all`` query +operator with the ``where()`` query builder method to match +documents that contain all the specified fields: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -837,12 +833,12 @@ in the {+server-docs-name+}. .. _laravel-query-builder-whereRaw: -Run Mongo Query API Queries Example -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Run MongoDB Operations Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``whereRaw()`` -query builder method to run a query written by using -MongoDB Query API syntax: +query builder method to run a query operation written by +using the MongoDB Query API syntax: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -861,6 +857,9 @@ The following code shows the equivalent MongoDB query: directors: { $in: [ "Yasujiro Ozu", "Sofia Coppola", "Federico Fellini" ] } }]}); +to learn more about the MongoDB Query API, see +:manual:`MongoDB Query API ` in the {+server-docs-name+}. + .. _laravel-query-builder-elemMatch: Match Array Elements Example @@ -888,7 +887,7 @@ Specify Cursor Timeout Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``timeout()`` method -to specify a period of time to spend on cursor operations. +to specify a maximum duration to wait for cursor operations to complet to completee. .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -985,10 +984,9 @@ the specified ``LineString`` GeoJSON object: Proximity Data for Nearby Matches Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``geoNear`` -aggregation operator with the ``raw()`` query builder method -to perform an aggregation that returns metadata such as -proximity information for each match: +The following example shows how to use the ``geoNear`` aggregation operator +with the ``raw()`` query builder method to perform an aggregation that returns +metadata, such as proximity information for each match: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -1102,3 +1100,4 @@ by the query: :dedent: :start-after: begin unset :end-before: end unset + From 41efa9bffbbee835a162a8dbf95464688a9e2088 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 15 Mar 2024 16:40:41 -0400 Subject: [PATCH 23/36] WIP --- docs/query-builder.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 144559f1a..eed6d3bec 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -707,7 +707,7 @@ to use the following MongoDB-specific query operations: - :ref:`Match documents that contain a particular data type in a field ` - :ref:`Match documents that contain a computed modulo value ` - :ref:`Match documents that match a regular expression ` -- :ref:`Run MongoDB operations ` +- :ref:`Run MongoDB Query API operations ` - :ref:`Match documents that contain array elements ` - :ref:`Specify a cursor timeout ` - :ref:`Match locations by using geospatial searches ` @@ -833,8 +833,8 @@ in the {+server-docs-name+}. .. _laravel-query-builder-whereRaw: -Run MongoDB Operations Example -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Run MongoDB Query API Operations Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``whereRaw()`` query builder method to run a query operation written by From 619b7b0b331e9c71dc7bc1df545de6c9d7d03621 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Mon, 25 Mar 2024 07:49:36 -0400 Subject: [PATCH 24/36] capitalize --- docs/query-builder.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index eed6d3bec..3a3c83cf0 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -857,7 +857,7 @@ The following code shows the equivalent MongoDB query: directors: { $in: [ "Yasujiro Ozu", "Sofia Coppola", "Federico Fellini" ] } }]}); -to learn more about the MongoDB Query API, see +To learn more about the MongoDB Query API, see :manual:`MongoDB Query API ` in the {+server-docs-name+}. .. _laravel-query-builder-elemMatch: @@ -984,8 +984,8 @@ the specified ``LineString`` GeoJSON object: Proximity Data for Nearby Matches Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``geoNear`` aggregation operator -with the ``raw()`` query builder method to perform an aggregation that returns +The following example shows how to use the ``geoNear`` aggregation operator +with the ``raw()`` query builder method to perform an aggregation that returns metadata, such as proximity information for each match: .. literalinclude:: /includes/query-builder/MovieController.php From 06efb4cab8b73a05edd0ae2d1e413e26e095568b Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Mon, 25 Mar 2024 09:03:49 -0400 Subject: [PATCH 25/36] single quotes --- .../query-builder/MovieController.php | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index c0a52beb7..39a1f147b 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -45,7 +45,7 @@ private function runWhere() ->get(); // end query where - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -59,7 +59,7 @@ private function runOrWhere() ->get(); // end query orWhere - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -73,7 +73,7 @@ private function runAndWhere() ->get(); // end query andWhere - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -90,7 +90,7 @@ private function runNestedLogical() })->get(); // end query nestedLogical - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -103,7 +103,7 @@ private function runWhereNot() ->get(); // end query whereNot - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -116,7 +116,7 @@ private function runWhereBetween() ->get(); // end query whereBetween - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -129,7 +129,7 @@ private function runWhereNull() ->get(); // end query whereNull - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -142,7 +142,7 @@ private function runWhereDate() ->get(); // end query whereDate - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -155,7 +155,7 @@ private function runRegex() ->get(); // end query whereRegex - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -167,7 +167,7 @@ private function runWhereIn() ->get(); // end query whereIn - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -179,7 +179,7 @@ private function runLike() ->get(); // end query like - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -202,7 +202,7 @@ private function runAll() ->getl(); // end query all - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -226,7 +226,7 @@ private function runType() ->get(); // end query type - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -238,7 +238,7 @@ private function runMod() ->get(); // end query modulo - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -273,7 +273,7 @@ private function runOrderBy() ->get(); // end query orderBy - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -369,7 +369,7 @@ private function runSkip() ->get(); // end query skip - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -386,7 +386,7 @@ private function runWhereRaw() ])->get(); // end query raw - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -398,7 +398,7 @@ private function runElemMatch() ->get(); // end query elemMatch - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -531,7 +531,7 @@ private function runCursorTimeout() ->get(); // end query cursor timeout - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } @@ -550,7 +550,7 @@ private function runUpsert() ); // end upsert - echo "{$result->toJson()}"; + echo '{$result->toJson()}'; return $result; } From b901c8645762dcefba56b2aa3f15a13e1b455380 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Mon, 25 Mar 2024 09:14:25 -0400 Subject: [PATCH 26/36] standardize value formatting, fix link --- docs/query-builder.txt | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 3a3c83cf0..d6c1702ad 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -161,7 +161,7 @@ Logical OR Example The following example shows how to chain the ``orWhere()`` query builder method to retrieve documents from the ``movies`` collection that either match the ``year`` -value of "1955" or match the title "Back to the Future": +value of ``1955`` or match the title "``Back to the Future``": .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -178,7 +178,7 @@ The following example shows how to chain the ``where()`` query builder method to retrieve documents from the ``movies`` collection that match both an ``imdb.rating`` value greater than "8.5" and a ``year`` value of less than -"1940": +``1940``: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -194,8 +194,8 @@ Logical NOT Example The following example shows how to chain the ``where()`` query builder method to retrieve documents from the ``movies`` collection that match both an ``imdb.rating`` -value greater than "8.5" and a ``year`` value of less than -"1940": +value greater than ``8.5`` and a ``year`` value of less than +``1940``: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -213,8 +213,8 @@ query builder method to retrieve documents from the ``movies`` collection that match both of the following conditions: -- ``imdb.rating`` value is greater than 8.5 -- ``year`` value is either 1986 or 1996 +- ``imdb.rating`` value is greater than ``8.5`` +- ``year`` value is either ``1986`` or ``1996`` .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -245,7 +245,7 @@ Numerical Range Example The following example shows how to use the ``whereBetween()`` query builder method to retrieve documents from the ``movies`` collection that contain an ``imdb.rating`` value -between "9" and "9.5": +between ``9`` and ``9.5``: .. io-code-block:: :copyable: true @@ -325,7 +325,7 @@ Match Dates Example The following example shows how to use the ``whereDate()`` query builder method to retrieve documents from the ``movies`` collection that match the specified date of -"2010-1-15" in the ``released`` field: +``2010-1-15`` in the ``released`` field: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -411,7 +411,7 @@ This example chains the following operations to match documents from the ``movies`` collection that contain a ``rated`` value of ``G`` and include the ``title`` field of one movie for each distinct ``runtime`` value: -- Match only documents that contain a ``rated`` field value of "G" by +- Match only documents that contain a ``rated`` field value of "``G``" by using the ``where()`` method - Group data by the distinct values of the ``runtime`` field, which is assigned the ``_id`` field, by using the ``groupBy()`` method @@ -621,7 +621,7 @@ Show a Subset of Fields and Array Values in the Results Example The following example shows how to use the ``project()`` query builder method to match documents that contain an -``imdb.rating`` value higher than "8.5" and return +``imdb.rating`` value higher than ``8.5`` and return only the following field values: - Title of the movie in the ``title`` @@ -690,7 +690,7 @@ only specific fields in the results. :end-before: end query projection with pagination To learn more about pagination, see -`Paginating Query Builder Results `__ +`Paginating Query Builder Results `__ in the Laravel documentation. .. _laravel-mongodb-read-query-builder: @@ -758,7 +758,7 @@ Match Array Size Example The following example shows how to pass the ``size`` query operator with the ``where()`` query builder method to match documents that contain a ``directors`` -field that contains an array of exactly "5" elements: +field that contains an array of exactly five elements: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -778,7 +778,7 @@ Match Data Type Example The following example shows how to pass the ``type`` query operator with the ``where()`` query builder method to match documents that contain a ``directors`` -field that contains an array of exactly "5" elements: +field that contains an array of exactly five elements: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -798,7 +798,7 @@ Match a Value Computed with Modulo Example The following example shows how to pass the ``mod`` query operator with the ``where()`` query builder method to match documents by using the expression -``year % 2 == 0``, which matches even values for +"``year % 2 == 0``", which matches even values for the ``year`` field: .. literalinclude:: /includes/query-builder/MovieController.php @@ -911,10 +911,10 @@ The examples in this section show the query builder syntax you can use to perform geospatial queries on GeoJSON or coordinate pair data to retrieve the following types of locations: -- Near a position -- Within a the boundary of a GeoJSON object -- Intersecting a GeoJSON object -- Proximity data for nearby matches +- :ref:`Near a position ` +- :ref:`Within a the boundary of a GeoJSON object ` +- :ref:`Intersecting a GeoJSON object ` +- :ref:`Proximity data for nearby matches ` .. important:: @@ -1048,7 +1048,7 @@ Decrement a Numerical Value Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``decrement()`` query builder -method to subtract "0.2" from the value of the ``imdb.rating`` field in the +method to subtract ``0.2`` from the value of the ``imdb.rating`` field in the matched document: .. literalinclude:: /includes/query-builder/MovieController.php @@ -1063,7 +1063,7 @@ Add an Array Element Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``push()`` query builder method to -add "Gary Cole" to the ``cast`` array field in the matched document: +add "``Gary Cole``" to the ``cast`` array field in the matched document: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -1077,7 +1077,7 @@ Remove an Array Element Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``pull()`` query builder method -to remove the "Adventure" value from the ``genres`` field from the document +to remove the "``Adventure``" value from the ``genres`` field from the document matched by the query: .. literalinclude:: /includes/query-builder/MovieController.php From 8bfe031c018a2a67c65043d52093be3f056bd817 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Mon, 25 Mar 2024 23:20:08 -0400 Subject: [PATCH 27/36] PRR fixes --- .../query-builder/MovieController.php | 2 +- docs/query-builder.txt | 80 ++++++++++--------- 2 files changed, 42 insertions(+), 40 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index 39a1f147b..2c9af9697 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -199,7 +199,7 @@ private function runAll() // begin query all $result = DB::collection('movies') ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) - ->getl(); + ->get(); // end query all echo '{$result->toJson()}'; diff --git a/docs/query-builder.txt b/docs/query-builder.txt index d6c1702ad..2d695df98 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -32,14 +32,14 @@ interface and syntax. by using Eloquent models, see :ref:`laravel-fundamentals-retrieve`. Laravel provides a **facade** to access the query builder class ``DB``, which -lets you perform database operations. Facades are static interfaces to -classes that make the syntax more concise, avoid runtime errors, and improve +lets you perform database operations. Facades, which are static interfaces to +classes, make the syntax more concise, avoid runtime errors, and improve testability. {+odm-short+} aliases the ``DB`` method ``table()`` as the ``collection()`` -method. Chain methods to specify the command and any constraints. Then, chain -the ``get()`` method at the end to run them on the MongoDB collection. The -following example shows the syntax of a query builder call: +method. Chain methods to specify commands and any constraints. Then, chain +the ``get()`` method at the end to run the methods and retrieve the results. +The following example shows the syntax of a query builder call: .. code-block:: php @@ -47,7 +47,7 @@ following example shows the syntax of a query builder call: // chain methods by using the "->" object operator ->get(); -This guide shows examples of the following types of query builder operations: +This guide provides examples of the following types of query builder operations: - :ref:`laravel-retrieve-query-builder` - :ref:`laravel-modify-results-query-builder` @@ -161,7 +161,7 @@ Logical OR Example The following example shows how to chain the ``orWhere()`` query builder method to retrieve documents from the ``movies`` collection that either match the ``year`` -value of ``1955`` or match the title "``Back to the Future``": +value of ``1955`` or match the title ``"Back to the Future"``: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -177,7 +177,7 @@ Logical AND Example The following example shows how to chain the ``where()`` query builder method to retrieve documents from the ``movies`` collection that match both an ``imdb.rating`` -value greater than "8.5" and a ``year`` value of less than +value greater than ``8.5`` and a ``year`` value of less than ``1940``: .. literalinclude:: /includes/query-builder/MovieController.php @@ -191,11 +191,11 @@ value greater than "8.5" and a ``year`` value of less than Logical NOT Example ^^^^^^^^^^^^^^^^^^^ -The following example shows how to chain the ``where()`` +The following example shows how to call the ``whereNot()`` query builder method to retrieve documents from the -``movies`` collection that match both an ``imdb.rating`` -value greater than ``8.5`` and a ``year`` value of less than -``1940``: +``movies`` collection that match documents that do not have an ``imdb.rating`` +value greater than ``2``. This is equivalent to matching all documents +that have an ``imdb.rating`` of less than or equal to ``2``: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -227,9 +227,8 @@ conditions: Ranges and Type Checks ~~~~~~~~~~~~~~~~~~~~~~ -The examples in this section show the query builder syntax you -can use to perform to match values by using the following range -queries and type check operations: +The examples in this section show the query builder syntax you can use to +match values by using the following range queries and type check operations: - :ref:`Values within a numerical range ` - :ref:`Null or missing values ` @@ -257,7 +256,7 @@ between ``9`` and ``9.5``: :end-before: end query whereBetween .. output:: - :language: json + :language: none :visible: false [ @@ -283,10 +282,6 @@ or field. :start-after: begin query whereNull :end-before: end query whereNull -.. seealso:: - - The ``exists()`` MongoDB operation performs the same query. - .. _laravel-query-builder-wherein: One or More Values of a Set Example @@ -389,11 +384,12 @@ Aggregations ~~~~~~~~~~~~ The examples in this section show the query builder syntax you -can use to perform aggregations, a set of calculations on the -query results, to return the following information: +can use to perform **aggregations**. Aggregations are operations +that compute values from a set of query result data. You can use +aggregations to compute and return the following information: - :ref:`Results grouped by common field values ` -- :ref:`Count the of results ` +- :ref:`Count the number of results ` - :ref:`Maximum value of a field ` - :ref:`Minimum value of a field ` - :ref:`Average value of a field ` @@ -411,7 +407,7 @@ This example chains the following operations to match documents from the ``movies`` collection that contain a ``rated`` value of ``G`` and include the ``title`` field of one movie for each distinct ``runtime`` value: -- Match only documents that contain a ``rated`` field value of "``G``" by +- Match only documents that contain a ``rated`` field value of ``"G"`` by using the ``where()`` method - Group data by the distinct values of the ``runtime`` field, which is assigned the ``_id`` field, by using the ``groupBy()`` method @@ -544,10 +540,11 @@ collection: Aggregate Matched Results Example ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The following example shows how to use the ``sum()`` -query builder method to return the numerical total of -the ``imdb.votes`` values from movies released in -after the year "2000": +The following example shows how to aggregate data +from results that match a query. The query matches all +movies after the year ``2000`` and computes the average +value of ``imdb.rating`` of those matches by using the +``avg()`` method: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -605,7 +602,7 @@ Omit a Specified Number of Results Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``skip()`` query builder method to -omit the first "4" results that match the filter specified in the ``title`` +omit the first four results that match the filter specified in the ``title`` field, sorted by the ``year`` value in descending order: .. literalinclude:: /includes/query-builder/MovieController.php @@ -680,7 +677,7 @@ Paginate the Results Example The following example shows how to use the ``paginate()`` query builder method to divide the entire ``movie`` collection into discrete result sets of 15 documents. The example also includes a sort order to arrange the results by -the ``imdb.votes`` field in descending order and a projection that includes +the ``imdb.votes`` field in ascending order and a projection that includes only specific fields in the results. .. literalinclude:: /includes/query-builder/MovieController.php @@ -777,8 +774,9 @@ Match Data Type Example The following example shows how to pass the ``type`` query operator with the ``where()`` query builder -method to match documents that contain a ``directors`` -field that contains an array of exactly five elements: +method to match documents that contain a type ``4`` value, +which corresponds to an array data type, in the +``released`` field. .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -798,7 +796,7 @@ Match a Value Computed with Modulo Example The following example shows how to pass the ``mod`` query operator with the ``where()`` query builder method to match documents by using the expression -"``year % 2 == 0``", which matches even values for +``"year % 2 == 0"``, which matches even values for the ``year`` field: .. literalinclude:: /includes/query-builder/MovieController.php @@ -846,7 +844,7 @@ using the MongoDB Query API syntax: :start-after: begin query raw :end-before: end query raw -The following code shows the equivalent MongoDB query: +The following code shows the equivalent MongoDB Query API syntax: .. code-block:: @@ -933,8 +931,9 @@ Near a Position Example ~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``near`` query operator -with the ``where()`` query builder method to match documents that contain the -field ``random_review``: +with the ``where()`` query builder method to match documents that +contain a location that is up to ``50`` meters from a GeoJSON Point +object: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -1003,6 +1002,9 @@ in the {+server-docs-name+}. MongoDB Write Operations ------------------------ +This section includes query builder examples that show how to use the +following MongoDB-specific write operations: + - :ref:`Upsert a document ` - :ref:`Increment a numerical value ` - :ref:`Decrement a numerical value ` @@ -1033,7 +1035,7 @@ Increment a Numerical Value Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``increment()`` -query builder method to add "3000" to the value of +query builder method to add ``3000`` to the value of the ``imdb.votes`` field in the matched document: .. literalinclude:: /includes/query-builder/MovieController.php @@ -1063,7 +1065,7 @@ Add an Array Element Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``push()`` query builder method to -add "``Gary Cole``" to the ``cast`` array field in the matched document: +add ``"Gary Cole"`` to the ``cast`` array field in the matched document: .. literalinclude:: /includes/query-builder/MovieController.php :language: php @@ -1077,7 +1079,7 @@ Remove an Array Element Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``pull()`` query builder method -to remove the "``Adventure``" value from the ``genres`` field from the document +to remove the ``"Adventure"`` value from the ``genres`` field from the document matched by the query: .. literalinclude:: /includes/query-builder/MovieController.php From 31cdfae601dbb9220b4232067cb9e8a465673e23 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Tue, 26 Mar 2024 00:46:49 -0400 Subject: [PATCH 28/36] tweaks --- .../query-builder/MovieController.php | 47 ++++++++++--------- docs/query-builder.txt | 23 ++++++++- 2 files changed, 45 insertions(+), 25 deletions(-) diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php index 2c9af9697..13d367458 100644 --- a/docs/includes/query-builder/MovieController.php +++ b/docs/includes/query-builder/MovieController.php @@ -9,6 +9,7 @@ use Illuminate\Support\Facades\DB; use MongoDB\BSON\Regex; use MongoDB\Laravel\Collection; +use Illuminate\Database\Query\Builder; use function print_r; use function view; @@ -45,7 +46,7 @@ private function runWhere() ->get(); // end query where - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -59,7 +60,7 @@ private function runOrWhere() ->get(); // end query orWhere - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -73,7 +74,7 @@ private function runAndWhere() ->get(); // end query andWhere - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -83,14 +84,14 @@ private function runNestedLogical() $result = DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', '>', 8.5) - ->where(function ($query) { + ->where(function (Builder $query) { return $query ->where('year', 1986) ->orWhere('year', 1996); })->get(); // end query nestedLogical - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -103,7 +104,7 @@ private function runWhereNot() ->get(); // end query whereNot - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -116,7 +117,7 @@ private function runWhereBetween() ->get(); // end query whereBetween - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -129,7 +130,7 @@ private function runWhereNull() ->get(); // end query whereNull - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -142,7 +143,7 @@ private function runWhereDate() ->get(); // end query whereDate - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -155,7 +156,7 @@ private function runRegex() ->get(); // end query whereRegex - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -167,7 +168,7 @@ private function runWhereIn() ->get(); // end query whereIn - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -175,11 +176,11 @@ private function runLike() { // begin query like $result = DB::collection('movies') - ->where('title', 'like', '%spider%man%') + ->where('title', 'like', '%spider_man%') ->get(); // end query like - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -202,7 +203,7 @@ private function runAll() ->get(); // end query all - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -226,7 +227,7 @@ private function runType() ->get(); // end query type - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -238,7 +239,7 @@ private function runMod() ->get(); // end query modulo - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -273,7 +274,7 @@ private function runOrderBy() ->get(); // end query orderBy - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -369,7 +370,7 @@ private function runSkip() ->get(); // end query skip - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -386,7 +387,7 @@ private function runWhereRaw() ])->get(); // end query raw - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -398,7 +399,7 @@ private function runElemMatch() ->get(); // end query elemMatch - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -531,7 +532,7 @@ private function runCursorTimeout() ->get(); // end query cursor timeout - echo '{$result->toJson()}'; + print_r($result->toJson()); return $result; } @@ -550,7 +551,7 @@ private function runUpsert() ); // end upsert - echo '{$result->toJson()}'; + print_r($result); return $result; } @@ -620,7 +621,7 @@ private function runUnset() public function show() { $result = null; - //$result = $this->runWhere(); + $result = $this->runWhere(); //$result = $this->runOrWhere(); //$result = $this->runAndWhere(); //$result = $this->runNestedLogical(); diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 2d695df98..30077e65e 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -211,7 +211,9 @@ Nested Logical Operator Group Example The following example shows how to chain the ``where()`` query builder method to retrieve documents from the ``movies`` collection that match both of the following -conditions: +conditions. This example passes a closure as the first +parameter of the ``where()`` query builder method to group +the logical OR group: - ``imdb.rating`` value is greater than ``8.5`` - ``year`` value is either ``1986`` or ``1996`` @@ -677,7 +679,7 @@ Paginate the Results Example The following example shows how to use the ``paginate()`` query builder method to divide the entire ``movie`` collection into discrete result sets of 15 documents. The example also includes a sort order to arrange the results by -the ``imdb.votes`` field in ascending order and a projection that includes +the ``imdb.votes`` field in descending order and a projection that includes only specific fields in the results. .. literalinclude:: /includes/query-builder/MovieController.php @@ -1029,6 +1031,9 @@ and the ``title`` field and value specified in the ``where()`` query operation: :start-after: begin upsert :end-before: end upsert +The ``update()`` query builder method returns the number of documents that the +operation updated or inserted. + .. _laravel-mongodb-query-builder-increment: Increment a Numerical Value Example @@ -1044,6 +1049,9 @@ the ``imdb.votes`` field in the matched document: :start-after: begin increment :end-before: end increment +The ``increment()`` query builder method returns the number of documents that the +operation updated. + .. _laravel-mongodb-query-builder-decrement: Decrement a Numerical Value Example @@ -1059,6 +1067,9 @@ matched document: :start-after: begin decrement :end-before: end decrement +The ``decrement()`` query builder method returns the number of documents that the +operation updated. + .. _laravel-mongodb-query-builder-push: Add an Array Element Example @@ -1073,6 +1084,9 @@ add ``"Gary Cole"`` to the ``cast`` array field in the matched document: :start-after: begin push :end-before: end push +The ``push()`` query builder method returns the number of documents that the +operation updated. + .. _laravel-mongodb-query-builder-pull: Remove an Array Element Example @@ -1088,6 +1102,9 @@ matched by the query: :start-after: begin pull :end-before: end pull +The ``pull()`` query builder method returns the number of documents that the +operation updated. + .. _laravel-mongodb-query-builder-unset: Remove a Field Example @@ -1103,3 +1120,5 @@ by the query: :start-after: begin unset :end-before: end unset +The ``unset()`` query builder method returns the number of documents that the +operation updated. \ No newline at end of file From 91525b2edbd90a08f1f4ccca89da947380f07558 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Tue, 26 Mar 2024 01:27:35 -0400 Subject: [PATCH 29/36] use unit test file --- .../query-builder/MovieController.php | 692 ------------------ .../query-builder/QueryBuilderTest.php | 551 ++++++++++++++ docs/query-builder.txt | 82 +-- 3 files changed, 592 insertions(+), 733 deletions(-) delete mode 100644 docs/includes/query-builder/MovieController.php create mode 100644 docs/includes/query-builder/QueryBuilderTest.php diff --git a/docs/includes/query-builder/MovieController.php b/docs/includes/query-builder/MovieController.php deleted file mode 100644 index 13d367458..000000000 --- a/docs/includes/query-builder/MovieController.php +++ /dev/null @@ -1,692 +0,0 @@ -collection('movies') - ->where('imdb.rating', 9.3) - ->get(); - // end query where - - print_r($result->toJson()); - return $result; - } - - private function runOrWhere() - { - // begin query orWhere - $result = DB::connection('mongodb') - ->collection('movies') - ->where('year', 1955) - ->orWhere('title', 'Back to the Future') - ->get(); - // end query orWhere - - print_r($result->toJson()); - return $result; - } - - private function runAndWhere() - { - // begin query andWhere - $result = DB::connection('mongodb') - ->collection('movies') - ->where('imdb.rating', '>', 8.5) - ->where('year', '<', 1940) - ->get(); - // end query andWhere - - print_r($result->toJson()); - return $result; - } - - private function runNestedLogical() - { - // begin query nestedLogical - $result = DB::connection('mongodb') - ->collection('movies') - ->where('imdb.rating', '>', 8.5) - ->where(function (Builder $query) { - return $query - ->where('year', 1986) - ->orWhere('year', 1996); - })->get(); - // end query nestedLogical - - print_r($result->toJson()); - return $result; - } - - private function runWhereNot() - { - // begin query whereNot - $result = DB::connection('mongodb') - ->collection('movies') - ->whereNot('imdb.rating', '>', 2) - ->get(); - // end query whereNot - - print_r($result->toJson()); - return $result; - } - - private function runWhereBetween() - { - // begin query whereBetween - $result = DB::connection('mongodb') - ->collection('movies') - ->whereBetween('imdb.rating', [9, 9.5]) - ->get(); - // end query whereBetween - - print_r($result->toJson()); - return $result; - } - - private function runWhereNull() - { - // begin query whereNull - $result = DB::connection('mongodb') - ->collection('movies') - ->whereNull('runtime') - ->get(); - // end query whereNull - - print_r($result->toJson()); - return $result; - } - - private function runWhereDate() - { - // begin query whereDate - $result = DB::connection('mongodb') - ->collection('movies') - ->whereDate('released', '2010-1-15') - ->get(); - // end query whereDate - - print_r($result->toJson()); - return $result; - } - - private function runRegex() - { - // begin query whereRegex - $result = DB::connection('mongodb') - ->collection('movies') - ->where('title', 'REGEX', new Regex('^the lord of .*', 'i')) - ->get(); - // end query whereRegex - - print_r($result->toJson()); - return $result; - } - - private function runWhereIn() - { - // begin query whereIn - $result = DB::collection('movies') - ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) - ->get(); - // end query whereIn - - print_r($result->toJson()); - return $result; - } - - private function runLike() - { - // begin query like - $result = DB::collection('movies') - ->where('title', 'like', '%spider_man%') - ->get(); - // end query like - - print_r($result->toJson()); - return $result; - } - - private function runExists() - { - // begin query exists - $result = DB::collection('movies') - ->exists('random_review', true); - // end query exists - - print_r($result); - return null; - } - - private function runAll() - { - // begin query all - $result = DB::collection('movies') - ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) - ->get(); - // end query all - - print_r($result->toJson()); - return $result; - } - - private function runSize() - { - // begin query size - $result = DB::collection('movies') - ->where('directors', 'size', 5) - ->get(); - // end query size - - print_r($result); - return null; - } - - private function runType() - { - // begin query type - $result = DB::collection('movies') - ->where('released', 'type', 4) - ->get(); - // end query type - - print_r($result->toJson()); - return $result; - } - - private function runMod() - { - // begin query modulo - $result = DB::collection('movies') - ->where('year', 'mod', [2, 0]) - ->get(); - // end query modulo - - print_r($result->toJson()); - return $result; - } - - private function runDistinct() - { - // begin query distinct - $result = DB::collection('movies') - ->distinct('year')->get(); - // end query distinct - print_r($result); - return null; - } - - private function runWhereDistinct() - { - // begin query where distinct - $result = DB::collection('movies') - ->where('imdb.rating', '>', 9) - ->distinct('year') - ->get(); - // end query where distinct - print_r($result); - return null; - } - - private function runOrderBy() - { - // begin query orderBy - $result = DB::collection('movies') - ->where('title', 'like', 'back to the future%') - ->orderBy('imdb.rating', 'desc') - ->get(); - // end query orderBy - - print_r($result->toJson()); - return $result; - } - - private function runGroupBy() - { - // begin query groupBy - $result = DB::collection('movies') - ->where('rated', 'G') - ->groupBy('runtime') - ->orderBy('runtime', 'asc') - ->get(['title']); - // end query groupBy - - $result = $result->toJson(); - print_r($result); - return null; - } - - private function runAggCount() - { - // begin aggregation count - $result = DB::collection('movies') - ->count(); - // end aggregation count - - print_r($result); - return null; - } - - private function runAggMax() - { - // begin aggregation max - $result = DB::collection('movies') - ->max('runtime'); - // end aggregation max - - print_r($result); - return null; - } - - private function runAggMin() - { - // begin aggregation min - $result = DB::collection('movies') - ->min('year'); - // end aggregation min - - print_r($result); - return null; - } - - private function runAggAvg() - { - // begin aggregation avg - $result = DB::collection('movies') - ->avg('imdb.rating'); - // end aggregation avg - - print_r($result); - return null; - } - - private function runAggSum() - { - // begin aggregation sum - $result = DB::collection('movies') - ->sum('imdb.votes'); - // end aggregation sum - - print_r($result); - return null; - } - - private function runAggWithFilter() - { - // begin aggregation with filter - $result = DB::collection('movies') - ->where('year', '>', 2000) - ->avg('imdb.rating'); - // end aggregation with filter - - print_r($result); - return null; - } - - private function runSkip() - { - // begin query skip - $result = DB::collection('movies') - ->where('title', 'like', 'star trek%') - ->orderBy('year', 'asc') - ->skip(4) - ->get(); - // end query skip - - print_r($result->toJson()); - return $result; - } - - private function runWhereRaw() - { - // begin query raw - $result = DB::collection('movies') - ->whereRaw([ - 'imdb.votes' => ['$gte' => 1000 ], - '$or' => [ - ['imdb.rating' => ['$gt' => 7]], - ['directors' => ['$in' => [ 'Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini' ]]], - ], - ])->get(); - // end query raw - - print_r($result->toJson()); - return $result; - } - - private function runElemMatch() - { - // begin query elemMatch - $result = DB::collection('movies') - ->where('writers', 'elemMatch', ['$in' => ['Maya Forbes', 'Eric Roth']]) - ->get(); - // end query elemMatch - - print_r($result->toJson()); - return $result; - } - - private function runNear() - { - // begin query near - $results = DB::collection('theaters') - ->where('location.geo', 'near', [ - '$geometry' => [ - 'type' => 'Point', - 'coordinates' => [ - -86.6423, - 33.6054, - ], - ], - '$maxDistance' => 50, - ])->get(); - // end query near - - print_r($results); - return null; - } - - private function runGeoWithin() - { - // begin query geoWithin - $results = DB::collection('theaters') - ->where('location.geo', 'geoWithin', [ - '$geometry' => [ - 'type' => 'Polygon', - 'coordinates' => [ - [ - [-72, 40], - [-74, 41], - [-72, 39], - [-72, 40], - ], - ], - ], - ])->get(); - // end query geoWithin - - print_r($results); - return null; - } - - private function runGeoIntersects() - { - // begin query geoIntersects - $results = DB::collection('theaters') - ->where('location.geo', 'geoIntersects', [ - '$geometry' => [ - 'type' => 'LineString', - 'coordinates' => [ - [-73.600525, 40.74416], - [-72.600525, 40.74416], - ], - ], - ])->get(); - // end query geoIntersects - - print_r($results); - return null; - } - - private function runGeoNear() - { - // begin query geoNear - - $results = DB::collection('theaters')->raw( - function (Collection $collection) { - return $collection->aggregate([ - [ - '$geoNear' => [ - 'near' => [ - 'type' => 'Point', - 'coordinates' => [-118.34, 34.10], - ], - 'distanceField' => 'dist.calculated', - 'maxDistance' => 500, - 'includeLocs' => 'dist.location', - 'spherical' => true, - ], - ], - ]); - }, - ); - // end query geoNear - - print_r($results->toArray()); - return null; - } - - private function runProjection() - { - // begin query projection - $result = DB::collection('movies') - ->where('imdb.rating', '>', 8.5) - ->project([ - 'title' => 1, - 'cast' => ['$slice' => [1, 3]], - ]) - ->get(); - // end query projection - print_r($result->toJson()); - return null; - } - - private function runProjectionWithPagination() - { - // begin query projection with pagination - $resultsPerPage = 15; - $projectionFields = ['title', 'runtime', 'imdb.rating']; - - $result = DB::collection('movies') - ->orderBy('imdb.votes', 'desc') - ->paginate($resultsPerPage, $projectionFields); - // end query projection with pagination - - print_r($result->toJson()); - return null; - } - - private function runCursorTimeout() - { - // begin query cursor timeout - $result = DB::collection('movies') - ->timeout(2) // value in seconds - ->where('year', 2001) - ->get(); - // end query cursor timeout - - print_r($result->toJson()); - return $result; - } - - private function runUpsert() - { - // begin upsert - $result = DB::collection('movies') - ->where('title', 'Will Hunting') - ->update( - [ - 'plot' => 'An autobiographical movie', - 'year' => 1998, - 'writers' => [ 'Will Hunting' ], - ], - ['upsert' => true], - ); - // end upsert - - print_r($result); - return $result; - } - - private function runIncrement() - { - // begin increment - $result = DB::collection('movies') - ->where('title', 'Field of Dreams') - ->increment('imdb.votes', 3000); - // end increment - - print_r($result); - return $result; - } - - private function runDecrement() - { - // begin decrement - $result = DB::collection('movies') - ->where('title', 'Sharknado') - ->decrement('imdb.rating', 0.2); - // end decrement - - print_r($result); - return $result; - } - - private function runPush() - { - // begin push - $result = DB::collection('movies') - ->where('title', 'Office Space') - ->push('cast', 'Gary Cole'); - // end push - - print_r($result); - return $result; - } - - private function runPull() - { - // begin pull - $result = DB::collection('movies') - ->where('title', 'Iron Man') - ->pull('genres', 'Adventure'); - // end pull - - print_r($result); - return $result; - } - - private function runUnset() - { - // begin unset - $result = DB::collection('movies') - ->where('title', 'Final Accord') - ->unset('tomatoes.viewer'); - // end unset - - print_r($result); - return $result; - } - - /** - * Display the specified resource. - */ - public function show() - { - $result = null; - $result = $this->runWhere(); - //$result = $this->runOrWhere(); - //$result = $this->runAndWhere(); - //$result = $this->runNestedLogical(); - //$result = $this->runWhereNot(); - //$result = $this->runWhereBetween(); - //$result = $this->runWhereNull(); - //$result = $this->runWhereDate(); - //$result = $this->runLike(); - //$result = $this->runExists(); - //$result = $this->runAll(); - //$result = $this->runSize(); - //$result = $this->runType(); - //$result = $this->runMod(); - //$result = $this->runRegex(); - //$result = $this->runWhereRaw(); - //result = $this->runElemMatch(); - //$result = $this->runNear(); - //$result = $this->runGeoWithin(); - //$result = $this->runGeoIntersects(); - //$result = $this->runGeoNear(); - //$result = $this->runWhereIn(); - //$result = $this->runDistinct(); - //$result = $this->runWhereDistinct(); - //$result = $this->runOrderBy(); - //$result = $this->runGroupBy(); - //$result = $this->runAggCount(); - //$result = $this->runAggMax(); - //$result = $this->runAggMin(); - //$result = $this->runAggAvg(); - //$result = $this->runAggSum(); - //$result = $this->runAggWithFilter(); - //$result = $this->runSkip(); - //$result = Movie::where('year', 1999)->get(); - //$result = $this->runProjection(); - //$result = $this->runProjectionWithPagination(); - //$result = $this->runCursorTimeout(); - //$result = $this->runUpsert(); - //$result = $this->runIncrement(); - //$result = $this->runDecrement(); - //$result = $this->runPush(); - //$result = $this->runPull(); - //$result = $this->runUnset(); - - //$result = Movie::first(); - return view('browse_movies', ['movies' => $result]); - } - - /** - * Show the form for editing the specified resource. - */ - public function edit(Movie $movie) - { - } - - /** - * Update the specified resource in storage. - */ - public function update(Request $request, Movie $movie) - { - } - - /** - * Remove the specified resource from storage. - */ - public function destroy(Movie $movie) - { - } -} diff --git a/docs/includes/query-builder/QueryBuilderTest.php b/docs/includes/query-builder/QueryBuilderTest.php new file mode 100644 index 000000000..1ecf5beb6 --- /dev/null +++ b/docs/includes/query-builder/QueryBuilderTest.php @@ -0,0 +1,551 @@ + + + // begin query where + $result = DB::connection('mongodb') + ->collection('movies') + ->where('imdb.rating', 9.3) + ->get(); + // end query where + } + + public function testOrWhere(): void + { + // + + // begin query orWhere + $result = DB::connection('mongodb') + ->collection('movies') + ->where('year', 1955) + ->orWhere('title', 'Back to the Future') + ->get(); + // end query orWhere + } + + public function testAndWhere(): void + { + // + + // begin query andWhere + $result = DB::connection('mongodb') + ->collection('movies') + ->where('imdb.rating', '>', 8.5) + ->where('year', '<', 1940) + ->get(); + // end query andWhere + } + + public function testNestedLogical(): void + { + // + + // begin query nestedLogical + $result = DB::connection('mongodb') + ->collection('movies') + ->where('imdb.rating', '>', 8.5) + ->where(function (Builder $query) { + return $query + ->where('year', 1986) + ->orWhere('year', 1996); + })->get(); + // end query nestedLogical + } + + public function testWhereNot(): void + { + // + + // begin query whereNot + $result = DB::connection('mongodb') + ->collection('movies') + ->whereNot('imdb.rating', '>', 2) + ->get(); + // end query whereNot + } + + public function testWhereBetween(): void + { + // + + // begin query whereBetween + $result = DB::connection('mongodb') + ->collection('movies') + ->whereBetween('imdb.rating', [9, 9.5]) + ->get(); + // end query whereBetween + } + + public function testWhereNull(): void + { + // + + // begin query whereDate + $result = DB::connection('mongodb') + ->collection('movies') + ->whereDate('released', '2010-1-15') + ->get(); + // end query whereDate + } + + public function testWhereRegex(): void + { + // + + // begin query whereRegex + $result = DB::connection('mongodb') + ->collection('movies') + ->where('title', 'REGEX', new Regex('^the lord of .*', 'i')) + ->get(); + // end query whereRegex + } + + public function testWhereIn(): void + { + // + + // begin query whereIn + $result = DB::collection('movies') + ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) + ->get(); + // end query whereIn + } + + public function testLike(): void + { + // + + // begin query like + $result = DB::collection('movies') + ->where('title', 'like', '%spider_man%') + ->get(); + // end query like + } + + public function testExists(): void + { + // + + // begin query exists + $result = DB::collection('movies') + ->exists('random_review', true); + // end query exists + } + + public function testAll(): void + { + // + + // begin query all + $result = DB::collection('movies') + ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) + ->get(); + // end query all + } + + public function testSize(): void + { + // + + // begin query size + $result = DB::collection('movies') + ->where('directors', 'size', 5) + ->get(); + // end query size + } + + public function testType(): void + { + // + + // begin query type + $result = DB::collection('movies') + ->where('released', 'type', 4) + ->get(); + // end query type + } + + public function testMod(): void + { + // + + // begin query modulo + $result = DB::collection('movies') + ->where('year', 'mod', [2, 0]) + ->get(); + // end query modulo + } + + public function testDistinct(): void + { + // + + // begin query distinct + $result = DB::collection('movies') + ->distinct('year')->get(); + // end query distinct + } + + public function testDistinct(): void + { + // + + // begin query distinct + $result = DB::collection('movies') + ->distinct('year')->get(); + // end query distinct + } + + public function testOrderBy(): void + { + // + + // begin query orderBy + $result = DB::collection('movies') + ->where('title', 'like', 'back to the future%') + ->orderBy('imdb.rating', 'desc') + ->get(); + // end query orderBy + } + + public function testGroupBy(): void + { + // + + // begin query groupBy + $result = DB::collection('movies') + ->where('rated', 'G') + ->groupBy('runtime') + ->orderBy('runtime', 'asc') + ->get(['title']); + // end query groupBy + } + + public function testAggCount(): void + { + // + + // begin aggregation count + $result = DB::collection('movies') + ->count(); + // end aggregation count + } + + public function testAggMax(): void + { + // + + // begin aggregation max + $result = DB::collection('movies') + ->max('runtime'); + // end aggregation max + } + + public function testAggMin(): void + { + // + + // begin aggregation min + $result = DB::collection('movies') + ->min('year'); + // end aggregation min + } + + public function testAggAvg(): void + { + // + + // begin aggregation avg + $result = DB::collection('movies') + ->avg('imdb.rating'); + // end aggregation avg + } + + public function testAggSum(): void + { + // + + // begin aggregation sum + $result = DB::collection('movies') + ->sum('imdb.votes'); + // end aggregation sum + } + + public function testAggWithFilter(): void + { + // + + // begin aggregation with filter + $result = DB::collection('movies') + ->where('year', '>', 2000) + ->avg('imdb.rating'); + // end aggregation with filter + } + + public function testSkip(): void + { + // + + // begin query skip + $result = DB::collection('movies') + ->where('title', 'like', 'star trek%') + ->orderBy('year', 'asc') + ->skip(4) + ->get(); + // end query skip + } + + public function testWhereRaw(): void + { + // + + // begin query raw + $result = DB::collection('movies') + ->whereRaw([ + 'imdb.votes' => ['$gte' => 1000 ], + '$or' => [ + ['imdb.rating' => ['$gt' => 7]], + ['directors' => ['$in' => [ 'Yasujiro Ozu', 'Sofia Coppola', 'Federico Fellini' ]]], + ], + ])->get(); + // end query raw + } + + public function testElemMatch(): void + { + // + + // begin query elemMatch + $result = DB::collection('movies') + ->where('writers', 'elemMatch', ['$in' => ['Maya Forbes', 'Eric Roth']]) + ->get(); + // end query elemMatch + } + + public function testNear(): void + { + // + // begin query near + $results = DB::collection('theaters') + ->where('location.geo', 'near', [ + '$geometry' => [ + 'type' => 'Point', + 'coordinates' => [ + -86.6423, + 33.6054, + ], + ], + '$maxDistance' => 50, + ])->get(); + // end query near + } + + public function testGeoWithin(): void + { + // + + // begin query geoWithin + $results = DB::collection('theaters') + ->where('location.geo', 'geoWithin', [ + '$geometry' => [ + 'type' => 'Polygon', + 'coordinates' => [ + [ + [-72, 40], + [-74, 41], + [-72, 39], + [-72, 40], + ], + ], + ], + ])->get(); + // end query geoWithin + } + + public function testGeoIntersects(): void + { + // + + // begin query geoIntersects + $results = DB::collection('theaters') + ->where('location.geo', 'geoIntersects', [ + '$geometry' => [ + 'type' => 'LineString', + 'coordinates' => [ + [-73.600525, 40.74416], + [-72.600525, 40.74416], + ], + ], + ])->get(); + // end query geoIntersects + } + + public function testGeoNear(): void + { + // + + // begin query geoNear + $results = DB::collection('theaters')->raw( + function (Collection $collection) { + return $collection->aggregate([ + [ + '$geoNear' => [ + 'near' => [ + 'type' => 'Point', + 'coordinates' => [-118.34, 34.10], + ], + 'distanceField' => 'dist.calculated', + 'maxDistance' => 500, + 'includeLocs' => 'dist.location', + 'spherical' => true, + ], + ], + ]); + }, + ); + // end query geoNear + } + + public function testProjection(): void + { + // + + // begin query projection + $result = DB::collection('movies') + ->where('imdb.rating', '>', 8.5) + ->project([ + 'title' => 1, + 'cast' => ['$slice' => [1, 3]], + ]) + ->get(); + // end query projection + } + + public function testProjectionWithPagination(): void + { + // + + // begin query projection with pagination + $resultsPerPage = 15; + $projectionFields = ['title', 'runtime', 'imdb.rating']; + + $result = DB::collection('movies') + ->orderBy('imdb.votes', 'desc') + ->paginate($resultsPerPage, $projectionFields); + // end query projection with pagination + } + + public function testCursorTimeout(): void + { + // + + // begin query cursor timeout + $result = DB::collection('movies') + ->timeout(2) // value in seconds + ->where('year', 2001) + ->get(); + // end query cursor timeout + } + + public function testUpsert(): void + { + // + + // begin upsert + $result = DB::collection('movies') + ->where('title', 'Will Hunting') + ->update( + [ + 'plot' => 'An autobiographical movie', + 'year' => 1998, + 'writers' => [ 'Will Hunting' ], + ], + ['upsert' => true], + ); + // end upsert + } + + public function testIncrement(): void + { + // + + // begin increment + $result = DB::collection('movies') + ->where('title', 'Field of Dreams') + ->increment('imdb.votes', 3000); + // end increment + } + + public function testDecrement(): void + { + // + + // begin decrement + $result = DB::collection('movies') + ->where('title', 'Sharknado') + ->decrement('imdb.rating', 0.2); + // end decrement + } + + public function testPush(): void + { + // + + // begin push + $result = DB::collection('movies') + ->where('title', 'Office Space') + ->push('cast', 'Gary Cole'); + // end push + } + + public function testPull(): void + { + // + + // begin pull + $result = DB::collection('movies') + ->where('title', 'Iron Man') + ->pull('genres', 'Adventure'); + // end pull + } + + public function testUnset(): void + { + // + + // begin unset + $result = DB::collection('movies') + ->where('title', 'Final Accord') + ->unset('tomatoes.viewer'); + // end unset + } + + public function testPull(): void + { + // + + // begin unset + $result = DB::collection('movies') + ->where('title', 'Final Accord') + ->unset('tomatoes.viewer'); + // end unset + } +} diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 30077e65e..a982b6232 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -94,7 +94,7 @@ by the query: .. io-code-block:: :copyable: true - .. input:: /includes/query-builder/MovieController.php + .. input:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query where @@ -163,7 +163,7 @@ query builder method to retrieve documents from the ``movies`` collection that either match the ``year`` value of ``1955`` or match the title ``"Back to the Future"``: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query orWhere @@ -180,7 +180,7 @@ query builder method to retrieve documents from the value greater than ``8.5`` and a ``year`` value of less than ``1940``: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query andWhere @@ -197,7 +197,7 @@ query builder method to retrieve documents from the value greater than ``2``. This is equivalent to matching all documents that have an ``imdb.rating`` of less than or equal to ``2``: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query whereNot @@ -218,7 +218,7 @@ the logical OR group: - ``imdb.rating`` value is greater than ``8.5`` - ``year`` value is either ``1986`` or ``1996`` -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query nestedLogical @@ -251,7 +251,7 @@ between ``9`` and ``9.5``: .. io-code-block:: :copyable: true - .. input:: /includes/query-builder/MovieController.php + .. input:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query whereBetween @@ -278,7 +278,7 @@ query builder method to retrieve documents from the ``movies`` collection that omit a ``runtime`` value or field. -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query whereNull @@ -297,7 +297,7 @@ query builder method to retrieve documents from the .. io-code-block:: :copyable: true - .. input:: /includes/query-builder/MovieController.php + .. input:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query whereIn @@ -324,7 +324,7 @@ query builder method to retrieve documents from the ``movies`` collection that match the specified date of ``2010-1-15`` in the ``released`` field: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query whereDate @@ -348,7 +348,7 @@ wildcard characters: .. io-code-block:: :copyable: true - .. input:: /includes/query-builder/MovieController.php + .. input:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query like @@ -374,7 +374,7 @@ The following example shows how to use the ``distinct()`` query builder method to retrieve all the different values of the ``year`` field for documents in the ``movies`` collections. -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query distinct @@ -427,7 +427,7 @@ This example chains the following operations to match documents from the .. io-code-block:: :copyable: true - .. input:: /includes/query-builder/MovieController.php + .. input:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query groupBy @@ -466,7 +466,7 @@ The following example shows how to use the ``count()`` query builder method to return the number of documents contained in the ``movies`` collection: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin aggregation count @@ -482,7 +482,7 @@ query builder method to return the highest numerical value of the ``runtime`` field from the entire ``movies`` collection: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin aggregation max @@ -498,7 +498,7 @@ query builder method to return the lowest numerical value of the ``year`` field from the entire ``movies`` collection: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin aggregation min @@ -514,7 +514,7 @@ query builder method to return the numerical average, or arithmetic mean, of the ``imdb.rating`` values from the entire ``movies`` collection. -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin aggregation avg @@ -531,7 +531,7 @@ the ``imdb.votes`` values from the entire ``movies`` collection: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin aggregation sum @@ -548,7 +548,7 @@ movies after the year ``2000`` and computes the average value of ``imdb.rating`` of those matches by using the ``avg()`` method: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin aggregation with filter @@ -581,7 +581,7 @@ the filter specified in the ``title`` field by the .. io-code-block:: :copyable: true - .. input:: /includes/query-builder/MovieController.php + .. input:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query orderBy @@ -607,7 +607,7 @@ The following example shows how to use the ``skip()`` query builder method to omit the first four results that match the filter specified in the ``title`` field, sorted by the ``year`` value in descending order: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query skip @@ -630,7 +630,7 @@ only the following field values: .. io-code-block:: :copyable: true - .. input:: /includes/query-builder/MovieController.php + .. input:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query projection @@ -682,7 +682,7 @@ documents. The example also includes a sort order to arrange the results by the ``imdb.votes`` field in descending order and a projection that includes only specific fields in the results. -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query projection with pagination @@ -720,7 +720,7 @@ The following example shows how to use the ``exists()`` query builder method to match documents that contain the field ``random_review``: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query exists @@ -739,7 +739,7 @@ The following example shows how to use the ``all`` query operator with the ``where()`` query builder method to match documents that contain all the specified fields: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query all @@ -759,7 +759,7 @@ query operator with the ``where()`` query builder method to match documents that contain a ``directors`` field that contains an array of exactly five elements: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query size @@ -780,7 +780,7 @@ method to match documents that contain a type ``4`` value, which corresponds to an array data type, in the ``released`` field. -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query type @@ -801,7 +801,7 @@ method to match documents by using the expression ``"year % 2 == 0"``, which matches even values for the ``year`` field: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query modulo @@ -821,7 +821,7 @@ query operator with the ``where()`` query builder method to match documents that contain a ``title`` field that matches the specified regular expression: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query whereRegex @@ -840,7 +840,7 @@ The following example shows how to use the ``whereRaw()`` query builder method to run a query operation written by using the MongoDB Query API syntax: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query raw @@ -871,7 +871,7 @@ method to match documents that contain an array element that matches at least one of the conditions in the specified query: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query elemMatch @@ -889,7 +889,7 @@ Specify Cursor Timeout Example The following example shows how to use the ``timeout()`` method to specify a maximum duration to wait for cursor operations to complet to completee. -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query cursor timeout @@ -937,7 +937,7 @@ with the ``where()`` query builder method to match documents that contain a location that is up to ``50`` meters from a GeoJSON Point object: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query near @@ -958,7 +958,7 @@ query builder method to match documents that contain a location within the bounds of the specified ``Polygon`` GeoJSON object: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query geoWithin @@ -974,7 +974,7 @@ query operator with the ``where()`` query builder method to match documents that contain a location that intersects with the specified ``LineString`` GeoJSON object: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query geoIntersects @@ -989,7 +989,7 @@ The following example shows how to use the ``geoNear`` aggregation operator with the ``raw()`` query builder method to perform an aggregation that returns metadata, such as proximity information for each match: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin query geoNear @@ -1025,7 +1025,7 @@ specified data if it does not exist. When setting the ``upsert`` option to ``true``, if the document does not exist, the command inserts both the data and the ``title`` field and value specified in the ``where()`` query operation: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin upsert @@ -1043,7 +1043,7 @@ The following example shows how to use the ``increment()`` query builder method to add ``3000`` to the value of the ``imdb.votes`` field in the matched document: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin increment @@ -1061,7 +1061,7 @@ The following example shows how to use the ``decrement()`` query builder method to subtract ``0.2`` from the value of the ``imdb.rating`` field in the matched document: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin decrement @@ -1078,7 +1078,7 @@ Add an Array Element Example The following example shows how to use the ``push()`` query builder method to add ``"Gary Cole"`` to the ``cast`` array field in the matched document: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin push @@ -1096,7 +1096,7 @@ The following example shows how to use the ``pull()`` query builder method to remove the ``"Adventure"`` value from the ``genres`` field from the document matched by the query: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin pull @@ -1114,7 +1114,7 @@ The following example shows how to use the ``unset()`` query builder method to remove the ``tomatoes.viewer`` field and value from the document matched by the query: -.. literalinclude:: /includes/query-builder/MovieController.php +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php :dedent: :start-after: begin unset From 131c65e7f1d2df087cc507040deaf216fc8edd87 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Tue, 26 Mar 2024 02:02:30 -0400 Subject: [PATCH 30/36] reorder --- .../query-builder/QueryBuilderTest.php | 287 +++++++++--------- 1 file changed, 139 insertions(+), 148 deletions(-) diff --git a/docs/includes/query-builder/QueryBuilderTest.php b/docs/includes/query-builder/QueryBuilderTest.php index 1ecf5beb6..af3e7ff84 100644 --- a/docs/includes/query-builder/QueryBuilderTest.php +++ b/docs/includes/query-builder/QueryBuilderTest.php @@ -54,6 +54,18 @@ public function testAndWhere(): void // end query andWhere } + public function testWhereNot(): void + { + // + + // begin query whereNot + $result = DB::connection('mongodb') + ->collection('movies') + ->whereNot('imdb.rating', '>', 2) + ->get(); + // end query whereNot + } + public function testNestedLogical(): void { // @@ -70,18 +82,6 @@ public function testNestedLogical(): void // end query nestedLogical } - public function testWhereNot(): void - { - // - - // begin query whereNot - $result = DB::connection('mongodb') - ->collection('movies') - ->whereNot('imdb.rating', '>', 2) - ->get(); - // end query whereNot - } - public function testWhereBetween(): void { // @@ -98,35 +98,35 @@ public function testWhereNull(): void { // - // begin query whereDate + // begin query whereNull $result = DB::connection('mongodb') ->collection('movies') - ->whereDate('released', '2010-1-15') + ->whereNull('runtime') ->get(); - // end query whereDate + // end query whereNull } - public function testWhereRegex(): void + public function testWhereIn(): void { // - // begin query whereRegex - $result = DB::connection('mongodb') - ->collection('movies') - ->where('title', 'REGEX', new Regex('^the lord of .*', 'i')) + // begin query whereIn + $result = DB::collection('movies') + ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) ->get(); - // end query whereRegex + // end query whereIn } - public function testWhereIn(): void + public function testWhereDate(): void { // - // begin query whereIn - $result = DB::collection('movies') - ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) + // begin query whereDate + $result = DB::connection('mongodb') + ->collection('movies') + ->whereDate('released', '2010-1-15') ->get(); - // end query whereIn + // end query whereDate } public function testLike(): void @@ -140,78 +140,88 @@ public function testLike(): void // end query like } - public function testExists(): void + public function testDistinct(): void { // - // begin query exists + // begin query distinct $result = DB::collection('movies') - ->exists('random_review', true); - // end query exists + ->distinct('year')->get(); + // end query distinct } - public function testAll(): void + public function testGroupBy(): void { // - // begin query all + // begin query groupBy $result = DB::collection('movies') - ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) - ->get(); - // end query all + ->where('rated', 'G') + ->groupBy('runtime') + ->orderBy('runtime', 'asc') + ->get(['title']); + // end query groupBy } - public function testSize(): void + public function testAggCount(): void { // - // begin query size + // begin aggregation count $result = DB::collection('movies') - ->where('directors', 'size', 5) - ->get(); - // end query size + ->count(); + // end aggregation count } - public function testType(): void + public function testAggMax(): void { // - // begin query type + // begin aggregation max $result = DB::collection('movies') - ->where('released', 'type', 4) - ->get(); - // end query type + ->max('runtime'); + // end aggregation max } - public function testMod(): void + public function testAggMin(): void { // - // begin query modulo + // begin aggregation min $result = DB::collection('movies') - ->where('year', 'mod', [2, 0]) - ->get(); - // end query modulo + ->min('year'); + // end aggregation min } - public function testDistinct(): void + public function testAggAvg(): void { // - // begin query distinct + // begin aggregation avg $result = DB::collection('movies') - ->distinct('year')->get(); - // end query distinct + ->avg('imdb.rating'); + // end aggregation avg } - public function testDistinct(): void + public function testAggSum(): void { // - // begin query distinct + // begin aggregation sum $result = DB::collection('movies') - ->distinct('year')->get(); - // end query distinct + ->sum('imdb.votes'); + // end aggregation sum + } + + public function testAggWithFilter(): void + { + // + + // begin aggregation with filter + $result = DB::collection('movies') + ->where('year', '>', 2000) + ->avg('imdb.rating'); + // end aggregation with filter } public function testOrderBy(): void @@ -226,91 +236,112 @@ public function testOrderBy(): void // end query orderBy } - public function testGroupBy(): void + public function testSkip(): void { // - // begin query groupBy + // begin query skip $result = DB::collection('movies') - ->where('rated', 'G') - ->groupBy('runtime') - ->orderBy('runtime', 'asc') - ->get(['title']); - // end query groupBy + ->where('title', 'like', 'star trek%') + ->orderBy('year', 'asc') + ->skip(4) + ->get(); + // end query skip } - public function testAggCount(): void + public function testProjection(): void { // - // begin aggregation count + // begin query projection $result = DB::collection('movies') - ->count(); - // end aggregation count + ->where('imdb.rating', '>', 8.5) + ->project([ + 'title' => 1, + 'cast' => ['$slice' => [1, 3]], + ]) + ->get(); + // end query projection } - public function testAggMax(): void + public function testProjectionWithPagination(): void { // - // begin aggregation max + // begin query projection with pagination + $resultsPerPage = 15; + $projectionFields = ['title', 'runtime', 'imdb.rating']; + $result = DB::collection('movies') - ->max('runtime'); - // end aggregation max + ->orderBy('imdb.votes', 'desc') + ->paginate($resultsPerPage, $projectionFields); + // end query projection with pagination } - public function testAggMin(): void + public function testExists(): void { // - // begin aggregation min + // begin query exists $result = DB::collection('movies') - ->min('year'); - // end aggregation min + ->exists('random_review', true); + // end query exists } - public function testAggAvg(): void + public function testAll(): void { // - // begin aggregation avg + // begin query all $result = DB::collection('movies') - ->avg('imdb.rating'); - // end aggregation avg + ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) + ->get(); + // end query all } - public function testAggSum(): void + public function testSize(): void { // - // begin aggregation sum + // begin query size $result = DB::collection('movies') - ->sum('imdb.votes'); - // end aggregation sum + ->where('directors', 'size', 5) + ->get(); + // end query size } - public function testAggWithFilter(): void + public function testType(): void { // - // begin aggregation with filter + // begin query type $result = DB::collection('movies') - ->where('year', '>', 2000) - ->avg('imdb.rating'); - // end aggregation with filter + ->where('released', 'type', 4) + ->get(); + // end query type } - public function testSkip(): void + public function testMod(): void { // - // begin query skip + // begin query modulo $result = DB::collection('movies') - ->where('title', 'like', 'star trek%') - ->orderBy('year', 'asc') - ->skip(4) + ->where('year', 'mod', [2, 0]) ->get(); - // end query skip + // end query modulo + } + + public function testWhereRegex(): void + { + // + + // begin query whereRegex + $result = DB::connection('mongodb') + ->collection('movies') + ->where('title', 'REGEX', new Regex('^the lord of .*', 'i')) + ->get(); + // end query whereRegex } public function testWhereRaw(): void @@ -340,6 +371,18 @@ public function testElemMatch(): void // end query elemMatch } + public function testCursorTimeout(): void + { + // + + // begin query cursor timeout + $result = DB::collection('movies') + ->timeout(2) // value in seconds + ->where('year', 2001) + ->get(); + // end query cursor timeout + } + public function testNear(): void { // @@ -424,47 +467,6 @@ function (Collection $collection) { // end query geoNear } - public function testProjection(): void - { - // - - // begin query projection - $result = DB::collection('movies') - ->where('imdb.rating', '>', 8.5) - ->project([ - 'title' => 1, - 'cast' => ['$slice' => [1, 3]], - ]) - ->get(); - // end query projection - } - - public function testProjectionWithPagination(): void - { - // - - // begin query projection with pagination - $resultsPerPage = 15; - $projectionFields = ['title', 'runtime', 'imdb.rating']; - - $result = DB::collection('movies') - ->orderBy('imdb.votes', 'desc') - ->paginate($resultsPerPage, $projectionFields); - // end query projection with pagination - } - - public function testCursorTimeout(): void - { - // - - // begin query cursor timeout - $result = DB::collection('movies') - ->timeout(2) // value in seconds - ->where('year', 2001) - ->get(); - // end query cursor timeout - } - public function testUpsert(): void { // @@ -537,15 +539,4 @@ public function testUnset(): void ->unset('tomatoes.viewer'); // end unset } - - public function testPull(): void - { - // - - // begin unset - $result = DB::collection('movies') - ->where('title', 'Final Accord') - ->unset('tomatoes.viewer'); - // end unset - } } From c69dded51439d52e614e51d9f8bdb52ce22d0eaa Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Tue, 26 Mar 2024 02:17:02 -0400 Subject: [PATCH 31/36] fixes --- docs/query-builder.txt | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index a982b6232..cd2d880ce 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -335,8 +335,8 @@ query builder method to retrieve documents from the Text Pattern Match Example ~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example shows how to use the ``like()`` -query builder method to retrieve documents from the +The following example shows how to use the ``like`` query operator +with the ``where()`` query builder method to retrieve documents from the ``movies`` collection by using a specified text pattern. Text patterns can contain text mixed with the following @@ -605,7 +605,7 @@ Omit a Specified Number of Results Example The following example shows how to use the ``skip()`` query builder method to omit the first four results that match the filter specified in the ``title`` -field, sorted by the ``year`` value in descending order: +field, sorted by the ``year`` value in ascending order: .. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php @@ -678,7 +678,7 @@ Paginate the Results Example The following example shows how to use the ``paginate()`` query builder method to divide the entire ``movie`` collection into discrete result sets of 15 -documents. The example also includes a sort order to arrange the results by +documents. The example also includes a sort order to arrange the results by the ``imdb.votes`` field in descending order and a projection that includes only specific fields in the results. @@ -887,7 +887,7 @@ Specify Cursor Timeout Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following example shows how to use the ``timeout()`` method -to specify a maximum duration to wait for cursor operations to complet to completee. +to specify a maximum duration to wait for cursor operations to complete. .. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php @@ -1021,8 +1021,8 @@ Upsert a Document Example The following example shows how to use the ``update()`` query builder method and ``upsert`` option to update the matching document or insert one with the -specified data if it does not exist. When setting the ``upsert`` option to -``true``, if the document does not exist, the command inserts both the data +specified data if it does not exist. When you set the ``upsert`` option to +``true`` and the document does not exist, the command inserts both the data and the ``title`` field and value specified in the ``where()`` query operation: .. literalinclude:: /includes/query-builder/QueryBuilderTest.php @@ -1121,4 +1121,4 @@ by the query: :end-before: end unset The ``unset()`` query builder method returns the number of documents that the -operation updated. \ No newline at end of file +operation updated. From 649e8795fe2a370e0f392222330491f4d04513e3 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Tue, 26 Mar 2024 15:32:29 -0400 Subject: [PATCH 32/36] PRR fixes --- docs/query-builder.txt | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index cd2d880ce..2e505454f 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -22,8 +22,8 @@ Overview In this guide, you can learn how to use the {+odm-short+} extension of the Laravel query builder to work with a MongoDB database. The query builder -lets you write queries for any supported database by using the same fluent -interface and syntax. +lets you use a single syntax and fluent interface to write queries for any +of supported database. .. note:: @@ -87,7 +87,7 @@ Where Method Example The following example shows how to use the ``where()`` query builder method to retrieve documents from the ``movies`` collection -that contain an ``imdb.votes`` field value of ``350``. Click the +that contain an ``imdb.rating`` field value of exactly ``9.3``. Click the :guilabel:`{+code-output-label+}` button to see the results returned by the query: @@ -161,7 +161,7 @@ Logical OR Example The following example shows how to chain the ``orWhere()`` query builder method to retrieve documents from the ``movies`` collection that either match the ``year`` -value of ``1955`` or match the title ``"Back to the Future"``: +value of ``1955`` or match the ``title`` value ``"Back to the Future"``: .. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php @@ -292,7 +292,7 @@ One or More Values of a Set Example The following example shows how to use the ``whereIn()`` query builder method to retrieve documents from the ``movies`` collection that match at least one of the -``title`` values in the specified set. +``title`` values in the specified set: .. io-code-block:: :copyable: true @@ -694,8 +694,8 @@ in the Laravel documentation. .. _laravel-mongodb-read-query-builder: -MongoDB Read Operations ------------------------ +Retrieve Data by Using MongoDB Operations +----------------------------------------- This section includes query builder examples that show how to use the following MongoDB-specific query operations: @@ -798,7 +798,7 @@ Match a Value Computed with Modulo Example The following example shows how to pass the ``mod`` query operator with the ``where()`` query builder method to match documents by using the expression -``"year % 2 == 0"``, which matches even values for +``year % 2 == 0``, which matches even values for the ``year`` field: .. literalinclude:: /includes/query-builder/QueryBuilderTest.php @@ -1001,8 +1001,8 @@ in the {+server-docs-name+}. .. _laravel-mongodb-write-query-builder: -MongoDB Write Operations ------------------------- +Write Data by Using MongoDB Write Operations +-------------------------------------------- This section includes query builder examples that show how to use the following MongoDB-specific write operations: From d79f852ec2c6333eded3e78cc9296e55280b005b Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Tue, 26 Mar 2024 15:38:27 -0400 Subject: [PATCH 33/36] PRR fix 2 --- docs/query-builder.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 2e505454f..817ad28fc 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -276,7 +276,7 @@ Null or Missing Values Example The following example shows how to use the ``whereNull()`` query builder method to retrieve documents from the ``movies`` collection that omit a ``runtime`` value -or field. +or field: .. literalinclude:: /includes/query-builder/QueryBuilderTest.php :language: php From 8a505173b3aa186c14fc977cd772304c3a4a0fc7 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 28 Mar 2024 11:09:58 -0400 Subject: [PATCH 34/36] grammar fix --- docs/query-builder.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 817ad28fc..7205daff3 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -23,7 +23,7 @@ Overview In this guide, you can learn how to use the {+odm-short+} extension of the Laravel query builder to work with a MongoDB database. The query builder lets you use a single syntax and fluent interface to write queries for any -of supported database. +supported database. .. note:: From e3708ff235b7b39e8d450ad34c116d80ed0e9c5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Fri, 5 Apr 2024 11:34:40 +0200 Subject: [PATCH 35/36] Update tests with data --- .../query-builder/QueryBuilderTest.php | 209 +++++++++++------- .../query-builder/sample_mflix.movies.json | 196 ++++++++++++++++ .../query-builder/sample_mflix.theaters.json | 39 ++++ 3 files changed, 358 insertions(+), 86 deletions(-) create mode 100644 docs/includes/query-builder/sample_mflix.movies.json create mode 100644 docs/includes/query-builder/sample_mflix.theaters.json diff --git a/docs/includes/query-builder/QueryBuilderTest.php b/docs/includes/query-builder/QueryBuilderTest.php index af3e7ff84..40705102d 100644 --- a/docs/includes/query-builder/QueryBuilderTest.php +++ b/docs/includes/query-builder/QueryBuilderTest.php @@ -5,33 +5,61 @@ namespace App\Http\Controllers; use Illuminate\Database\Query\Builder; +use Illuminate\Pagination\AbstractPaginator; use Illuminate\Support\Facades\DB; use MongoDB\BSON\Regex; use MongoDB\Laravel\Collection; use MongoDB\Laravel\Tests\TestCase; +use function file_get_contents; +use function json_decode; + class QueryBuilderTest extends TestCase { - /** - * @runInSeparateProcess - * @preserveGlobalState disabled - */ - public function testWhere(): void + protected function setUp(): void + { + parent::setUp(); + + $db = DB::connection('mongodb'); + $db->collection('movies') + ->insert(json_decode(file_get_contents(__DIR__ . '/sample_mflix.movies.json'), true)); + } + + protected function importTheaters(): void { - // + $db = DB::connection('mongodb'); + + $db->collection('theaters') + ->insert(json_decode(file_get_contents(__DIR__ . '/sample_mflix.theaters.json'), true)); + + $db->collection('theaters') + ->raw() + ->createIndex(['location.geo' => '2dsphere']); + } + + protected function tearDown(): void + { + $db = DB::connection('mongodb'); + $db->collection('movies')->raw()->drop(); + $db->collection('theaters')->raw()->drop(); + + parent::tearDown(); + } + public function testWhere(): void + { // begin query where $result = DB::connection('mongodb') ->collection('movies') ->where('imdb.rating', 9.3) ->get(); // end query where + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testOrWhere(): void { - // - // begin query orWhere $result = DB::connection('mongodb') ->collection('movies') @@ -39,12 +67,12 @@ public function testOrWhere(): void ->orWhere('title', 'Back to the Future') ->get(); // end query orWhere + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testAndWhere(): void { - // - // begin query andWhere $result = DB::connection('mongodb') ->collection('movies') @@ -52,24 +80,24 @@ public function testAndWhere(): void ->where('year', '<', 1940) ->get(); // end query andWhere + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testWhereNot(): void { - // - // begin query whereNot $result = DB::connection('mongodb') ->collection('movies') ->whereNot('imdb.rating', '>', 2) ->get(); // end query whereNot + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testNestedLogical(): void { - // - // begin query nestedLogical $result = DB::connection('mongodb') ->collection('movies') @@ -80,80 +108,80 @@ public function testNestedLogical(): void ->orWhere('year', 1996); })->get(); // end query nestedLogical + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testWhereBetween(): void { - // - // begin query whereBetween $result = DB::connection('mongodb') ->collection('movies') ->whereBetween('imdb.rating', [9, 9.5]) ->get(); // end query whereBetween + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testWhereNull(): void { - // - // begin query whereNull $result = DB::connection('mongodb') ->collection('movies') ->whereNull('runtime') ->get(); // end query whereNull + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testWhereIn(): void { - // - // begin query whereIn $result = DB::collection('movies') ->whereIn('title', ['Toy Story', 'Shrek 2', 'Johnny English']) ->get(); // end query whereIn + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testWhereDate(): void { - // - // begin query whereDate $result = DB::connection('mongodb') ->collection('movies') ->whereDate('released', '2010-1-15') ->get(); // end query whereDate + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testLike(): void { - // - // begin query like $result = DB::collection('movies') ->where('title', 'like', '%spider_man%') ->get(); // end query like + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testDistinct(): void { - // - // begin query distinct $result = DB::collection('movies') ->distinct('year')->get(); // end query distinct + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testGroupBy(): void { - // - // begin query groupBy $result = DB::collection('movies') ->where('rated', 'G') @@ -161,85 +189,86 @@ public function testGroupBy(): void ->orderBy('runtime', 'asc') ->get(['title']); // end query groupBy + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testAggCount(): void { - // - // begin aggregation count $result = DB::collection('movies') ->count(); // end aggregation count + + $this->assertIsInt($result); } public function testAggMax(): void { - // - // begin aggregation max $result = DB::collection('movies') ->max('runtime'); // end aggregation max + + $this->assertIsInt($result); } public function testAggMin(): void { - // - // begin aggregation min $result = DB::collection('movies') ->min('year'); // end aggregation min + + $this->assertIsInt($result); } public function testAggAvg(): void { - // - // begin aggregation avg $result = DB::collection('movies') ->avg('imdb.rating'); + //->avg('year'); // end aggregation avg + + $this->assertIsFloat($result); } public function testAggSum(): void { - // - // begin aggregation sum $result = DB::collection('movies') ->sum('imdb.votes'); // end aggregation sum + + $this->assertIsInt($result); } public function testAggWithFilter(): void { - // - // begin aggregation with filter $result = DB::collection('movies') ->where('year', '>', 2000) ->avg('imdb.rating'); // end aggregation with filter + + $this->assertIsFloat($result); } public function testOrderBy(): void { - // - // begin query orderBy $result = DB::collection('movies') ->where('title', 'like', 'back to the future%') ->orderBy('imdb.rating', 'desc') ->get(); // end query orderBy + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testSkip(): void { - // - // begin query skip $result = DB::collection('movies') ->where('title', 'like', 'star trek%') @@ -247,12 +276,12 @@ public function testSkip(): void ->skip(4) ->get(); // end query skip + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testProjection(): void { - // - // begin query projection $result = DB::collection('movies') ->where('imdb.rating', '>', 8.5) @@ -262,12 +291,12 @@ public function testProjection(): void ]) ->get(); // end query projection + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testProjectionWithPagination(): void { - // - // begin query projection with pagination $resultsPerPage = 15; $projectionFields = ['title', 'runtime', 'imdb.rating']; @@ -276,78 +305,78 @@ public function testProjectionWithPagination(): void ->orderBy('imdb.votes', 'desc') ->paginate($resultsPerPage, $projectionFields); // end query projection with pagination + + $this->assertInstanceOf(AbstractPaginator::class, $result); } public function testExists(): void { - // - // begin query exists $result = DB::collection('movies') ->exists('random_review', true); // end query exists + + $this->assertIsBool($result); } public function testAll(): void { - // - // begin query all $result = DB::collection('movies') ->where('movies', 'all', ['title', 'rated', 'imdb.rating']) ->get(); // end query all + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testSize(): void { - // - // begin query size $result = DB::collection('movies') ->where('directors', 'size', 5) ->get(); // end query size + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testType(): void { - // - // begin query type $result = DB::collection('movies') ->where('released', 'type', 4) ->get(); // end query type + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testMod(): void { - // - // begin query modulo $result = DB::collection('movies') ->where('year', 'mod', [2, 0]) ->get(); // end query modulo + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testWhereRegex(): void { - // - // begin query whereRegex $result = DB::connection('mongodb') ->collection('movies') ->where('title', 'REGEX', new Regex('^the lord of .*', 'i')) ->get(); // end query whereRegex + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testWhereRaw(): void { - // - // begin query raw $result = DB::collection('movies') ->whereRaw([ @@ -358,35 +387,38 @@ public function testWhereRaw(): void ], ])->get(); // end query raw + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testElemMatch(): void { - // - // begin query elemMatch $result = DB::collection('movies') ->where('writers', 'elemMatch', ['$in' => ['Maya Forbes', 'Eric Roth']]) ->get(); // end query elemMatch + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testCursorTimeout(): void { - // - // begin query cursor timeout $result = DB::collection('movies') ->timeout(2) // value in seconds ->where('year', 2001) ->get(); // end query cursor timeout + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); } public function testNear(): void { - // - // begin query near + $this->importTheaters(); + + // begin query near $results = DB::collection('theaters') ->where('location.geo', 'near', [ '$geometry' => [ @@ -399,12 +431,12 @@ public function testNear(): void '$maxDistance' => 50, ])->get(); // end query near + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $results); } public function testGeoWithin(): void { - // - // begin query geoWithin $results = DB::collection('theaters') ->where('location.geo', 'geoWithin', [ @@ -421,12 +453,12 @@ public function testGeoWithin(): void ], ])->get(); // end query geoWithin + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $results); } public function testGeoIntersects(): void { - // - // begin query geoIntersects $results = DB::collection('theaters') ->where('location.geo', 'geoIntersects', [ @@ -439,11 +471,13 @@ public function testGeoIntersects(): void ], ])->get(); // end query geoIntersects + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $results); } public function testGeoNear(): void { - // + $this->importTheaters(); // begin query geoNear $results = DB::collection('theaters')->raw( @@ -463,14 +497,15 @@ function (Collection $collection) { ], ]); }, - ); + )->toArray(); // end query geoNear + + $this->assertIsArray($results); + $this->assertSame(8900, $results[0]['theaterId']); } public function testUpsert(): void { - // - // begin upsert $result = DB::collection('movies') ->where('title', 'Will Hunting') @@ -483,60 +518,62 @@ public function testUpsert(): void ['upsert' => true], ); // end upsert + + $this->assertIsInt($result); } public function testIncrement(): void { - // - // begin increment $result = DB::collection('movies') ->where('title', 'Field of Dreams') ->increment('imdb.votes', 3000); // end increment + + $this->assertIsInt($result); } public function testDecrement(): void { - // - // begin decrement $result = DB::collection('movies') ->where('title', 'Sharknado') ->decrement('imdb.rating', 0.2); // end decrement + + $this->assertIsInt($result); } public function testPush(): void { - // - // begin push $result = DB::collection('movies') ->where('title', 'Office Space') ->push('cast', 'Gary Cole'); // end push + + $this->assertIsInt($result); } public function testPull(): void { - // - // begin pull $result = DB::collection('movies') ->where('title', 'Iron Man') ->pull('genres', 'Adventure'); // end pull + + $this->assertIsInt($result); } public function testUnset(): void { - // - // begin unset $result = DB::collection('movies') ->where('title', 'Final Accord') ->unset('tomatoes.viewer'); // end unset + + $this->assertIsInt($result); } } diff --git a/docs/includes/query-builder/sample_mflix.movies.json b/docs/includes/query-builder/sample_mflix.movies.json new file mode 100644 index 000000000..57873754e --- /dev/null +++ b/docs/includes/query-builder/sample_mflix.movies.json @@ -0,0 +1,196 @@ +[ + { + "genres": [ + "Short" + ], + "runtime": 1, + "cast": [ + "Charles Kayser", + "John Ott" + ], + "title": "Blacksmith Scene", + "directors": [ + "William K.L. Dickson" + ], + "rated": "UNRATED", + "year": 1893, + "imdb": { + "rating": 6.2, + "votes": 1189, + "id": 5 + }, + "tomatoes": { + "viewer": { + "rating": 3, + "numReviews": 184, + "meter": 32 + } + } + }, + { + "genres": [ + "Short", + "Western" + ], + "runtime": 11, + "cast": [ + "A.C. Abadie", + "Gilbert M. 'Broncho Billy' Anderson", + "George Barnes", + "Justus D. Barnes" + ], + "title": "The Great Train Robbery", + "directors": [ + "Edwin S. Porter" + ], + "rated": "TV-G", + "year": 1903, + "imdb": { + "rating": 7.4, + "votes": 9847, + "id": 439 + }, + "tomatoes": { + "viewer": { + "rating": 3.7, + "numReviews": 2559, + "meter": 75 + } + } + }, + { + "genres": [ + "Short", + "Drama", + "Fantasy" + ], + "runtime": 14, + "rated": "UNRATED", + "cast": [ + "Martin Fuller", + "Mrs. William Bechtel", + "Walter Edwin", + "Ethel Jewett" + ], + "title": "The Land Beyond the Sunset", + "directors": [ + "Harold M. Shaw" + ], + "writers": [ + "Dorothy G. Shore" + ], + "year": 1912, + "imdb": { + "rating": 7.1, + "votes": 448, + "id": 488 + }, + "tomatoes": { + "viewer": { + "rating": 3.7, + "numReviews": 53, + "meter": 67 + } + } + }, + { + "genres": [ + "Short", + "Drama" + ], + "runtime": 14, + "cast": [ + "Frank Powell", + "Grace Henderson", + "James Kirkwood", + "Linda Arvidson" + ], + "title": "A Corner in Wheat", + "directors": [ + "D.W. Griffith" + ], + "rated": "G", + "year": 1909, + "imdb": { + "rating": 6.6, + "votes": 1375, + "id": 832 + }, + "tomatoes": { + "viewer": { + "rating": 3.6, + "numReviews": 109, + "meter": 73 + } + } + }, + { + "genres": [ + "Animation", + "Short", + "Comedy" + ], + "runtime": 7, + "cast": [ + "Winsor McCay" + ], + "title": "Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics", + "directors": [ + "Winsor McCay", + "J. Stuart Blackton" + ], + "writers": [ + "Winsor McCay (comic strip \"Little Nemo in Slumberland\")", + "Winsor McCay (screenplay)" + ], + "year": 1911, + "imdb": { + "rating": 7.3, + "votes": 1034, + "id": 1737 + }, + "tomatoes": { + "viewer": { + "rating": 3.4, + "numReviews": 89, + "meter": 47 + } + } + }, + { + "genres": [ + "Comedy", + "Fantasy", + "Romance" + ], + "runtime": 118, + "cast": [ + "Meg Ryan", + "Hugh Jackman", + "Liev Schreiber", + "Breckin Meyer" + ], + "title": "Kate & Leopold", + "directors": [ + "James Mangold" + ], + "writers": [ + "Steven Rogers (story)", + "James Mangold (screenplay)", + "Steven Rogers (screenplay)" + ], + "year": 2001, + "imdb": { + "rating": 6.3, + "votes": 59951, + "id": 35423 + }, + "tomatoes": { + "viewer": { + "rating": 3, + "numReviews": 189426, + "meter": 62 + } + } + } +] diff --git a/docs/includes/query-builder/sample_mflix.theaters.json b/docs/includes/query-builder/sample_mflix.theaters.json new file mode 100644 index 000000000..b8d55381c --- /dev/null +++ b/docs/includes/query-builder/sample_mflix.theaters.json @@ -0,0 +1,39 @@ +[ + { + "theaterId": 1000, + "location": { + "address": { + "street1": "340 W Market", + "city": "Bloomington", + "state": "MN", + "zipcode": "55425" + }, + "geo": { + "type": "Point", + "coordinates": [ + -93.24565, + 44.85466 + ] + } + } + }, + { + "theaterId": 8900, + "location": { + "address": { + "street1": "6801 Hollywood Blvd", + "street2": null, + "city": "Hollywood", + "state": "CA", + "zipcode": "90028" + }, + "geo": { + "type": "Point", + "coordinates": [ + -118.340261, + 34.102593 + ] + } + } + } +] From 0a1fc6842dde262c18682c9f1c3b80a6e2c953e6 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 5 Apr 2024 10:58:27 -0400 Subject: [PATCH 36/36] add link to schema builder for info on creating geospatial indexes --- docs/eloquent-models/schema-builder.txt | 2 ++ docs/query-builder.txt | 8 ++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/eloquent-models/schema-builder.txt b/docs/eloquent-models/schema-builder.txt index 9fd845b55..39c6a9887 100644 --- a/docs/eloquent-models/schema-builder.txt +++ b/docs/eloquent-models/schema-builder.txt @@ -324,6 +324,8 @@ field: To learn more about these indexes, see :manual:`Index Properties ` in the {+server-docs-name+}. +.. _laravel-eloquent-geospatial-index: + Create a Geospatial Index ~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 7205daff3..9650df09b 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -918,10 +918,10 @@ pair data to retrieve the following types of locations: .. important:: - To perform GeoJSON queries in MongoDB, you must create either - ``2d`` or ``2dsphere`` index on the collection. To learn more - about these indexes, see :manual:`Geospatial Indexes ` - in the {+server-docs-name+}. + To perform GeoJSON queries in MongoDB, you must create either ``2d`` or + ``2dsphere`` index on the collection. To learn how to create geospatial + indexes, see the :ref:`laravel-eloquent-geospatial-index` section in the + Schema Builder guide. To learn more about GeoJSON objects that MongoDB supports, see :manual:`GeoJSON Objects `