-
Notifications
You must be signed in to change notification settings - Fork 1.4k
DOCSP-35947: write operations modify documents #2808
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ccho-mongodb
merged 26 commits into
mongodb:4.1-base-docs-write-operations
from
ccho-mongodb:DOCSP-35947-write-operations-modify-documents
Apr 8, 2024
Merged
Changes from 25 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
8fbbcc4
DOCSP-35948: Write operations
a5a75ca
add examples
a678179
apply phpcbf formatting
ccho-mongodb eea96e5
wip
88024a5
apply phpcbf formatting
ccho-mongodb 24fdd13
add date info
77bdbec
apply phpcbf formatting
ccho-mongodb 831f06e
update title of read operations
d813f23
grammar fixes
a194e60
DOCSP-35947: write operations - modify documents
2582bd5
apply phpcbf formatting
ccho-mongodb 86ff663
misc fixes
4dc106a
rst fixes
678490e
fixes
8ff6872
fix
44eb655
fix
60a6cfb
fix rst
a9d072c
concise sentence
79037d2
linebreaks
78bc0e7
double backslash
1d77153
fix
146cecb
PRR fixes
39dc447
PRR fixes 2
cfac53e
PRR fixes 3
1e6269f
remove comments from tests
70fbf47
Merge branch '4.1-base-docs-write-operations' into DOCSP-35947-write-…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
.. _laravel_fundamentals: | ||
|
||
============ | ||
Fundamentals | ||
============ | ||
|
||
.. facet:: | ||
:name: genre | ||
:values: reference | ||
|
||
.. meta:: | ||
:keywords: php framework, odm | ||
|
||
.. toctree:: | ||
:titlesonly: | ||
:maxdepth: 1 | ||
|
||
/fundamentals/read-operations | ||
/fundamentals/write-operations | ||
|
||
Learn how to use the {+odm-long+} to perform the following tasks: | ||
|
||
- :ref:`Read Operations <laravel-fundamentals-read-ops>` | ||
- :ref:`Write Operations <laravel-fundamentals-write-ops>` | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,250 @@ | ||
.. _laravel-fundamentals-write-ops: | ||
|
||
================ | ||
Write Operations | ||
================ | ||
|
||
.. facet:: | ||
:name: genre | ||
:values: tutorial | ||
|
||
.. meta:: | ||
:keywords: insert, insert one, code example, mass assignment, eloquent model | ||
|
||
.. contents:: On this page | ||
:local: | ||
:backlinks: none | ||
:depth: 2 | ||
:class: singlecol | ||
|
||
Overview | ||
-------- | ||
|
||
In this guide, you can learn how to use {+odm-short+} to perform | ||
**write operations** on your MongoDB collections. Write operations include | ||
inserting, updating, and deleting data based on specified criteria. | ||
|
||
This guide shows you how to perform the following tasks: | ||
|
||
- :ref:`laravel-fundamentals-insert-documents` | ||
- :ref:`laravel-fundamentals-modify-documents` | ||
- Delete Documents | ||
|
||
.. _laravel-fundamentals-write-sample-model: | ||
|
||
Sample Model | ||
~~~~~~~~~~~~ | ||
|
||
The write operations in this guide reference the following Eloquent model class: | ||
|
||
.. literalinclude:: /includes/fundamentals/write-operations/Concert.php | ||
:language: php | ||
:dedent: | ||
:caption: Concert.php | ||
|
||
.. tip:: | ||
|
||
The ``$fillable`` attribute lets you use Laravel mass assignment for insert | ||
operations. To learn more about mass assignment, see :ref:`laravel-model-mass-assignment` | ||
in the Eloquent Model Class documentation. | ||
|
||
The ``$casts`` attribute instructs Laravel to convert attributes to common | ||
data types. To learn more, see `Attribute Casting <https://laravel.com/docs/{+laravel-docs-version+}/eloquent-mutators#attribute-casting>`__ | ||
in the Laravel documentation. | ||
|
||
.. _laravel-fundamentals-insert-documents: | ||
|
||
Insert Documents | ||
---------------- | ||
|
||
In this section, you can learn how to insert documents into MongoDB collections | ||
from your Laravel application by using the {+odm-long+}. | ||
|
||
When you insert the documents, ensure the data does not violate any | ||
unique indexes on the collection. When inserting the first document of a | ||
collection or creating a new collection, MongoDB automatically creates a | ||
unique index on the ``_id`` field. | ||
|
||
For more information on creating indexes on MongoDB collections by using the | ||
Laravel schema builder, see the :ref:`laravel-eloquent-indexes` section | ||
of the Schema Builder documentation. | ||
|
||
To learn more about Eloquent models in {+odm-short+}, see the :ref:`laravel-eloquent-models` | ||
section. | ||
|
||
Insert a Document Examples | ||
~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
||
These examples show how to use the ``save()`` Eloquent method to insert an | ||
instance of a ``Concert`` model as a MongoDB document. | ||
|
||
When the ``save()`` method succeeds, you can access the model instance on | ||
which you called the method. | ||
|
||
If the operation fails, the model instance is assigned a null value. | ||
|
||
This example code performs the following actions: | ||
|
||
- Creates a new instance of the ``Concert`` model | ||
- Assigns string values to the ``performer`` and ``venue`` fields | ||
- Assigns an array of strings to the ``genre`` field | ||
- Assigns a number to the ``ticketsSold`` field | ||
- Assigns a date to the ``performanceDate`` field by using the ``Carbon`` | ||
package | ||
- Inserts the document by calling the ``save()`` method | ||
|
||
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php | ||
:language: php | ||
:dedent: | ||
:start-after: begin model insert one | ||
:end-before: end model insert one | ||
|
||
You can retrieve the inserted document's ``_id`` value by accessing the model's | ||
``id`` member, as shown in the following code example: | ||
|
||
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php | ||
:language: php | ||
:dedent: | ||
:start-after: begin inserted id | ||
:end-before: end inserted id | ||
|
||
If you enable mass assignment by defining either the ``$fillable`` or | ||
``$guarded`` attributes, you can use the Eloquent model ``create()`` method | ||
to perform the insert in a single call, as shown in the following example: | ||
|
||
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php | ||
:language: php | ||
:dedent: | ||
:start-after: begin model insert one mass assign | ||
:end-before: end model insert one mass assign | ||
|
||
To learn more about the Carbon PHP API extension, see the | ||
:github:`Carbon <briannesbitt/Carbon>` GitHub repository. | ||
|
||
Insert Multiple Documents Example | ||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
||
This example shows how to use the ``insert()`` Eloquent method to insert | ||
multiple instances of a ``Concert`` model as MongoDB documents. This bulk | ||
insert method reduces the number of calls your application needs to make | ||
to save the documents. | ||
|
||
When the ``insert()`` method succeeds, it returns the value ``1``. | ||
|
||
If it fails, it throws an exception. | ||
|
||
The example code saves multiple models in a single call by passing them as | ||
an array to the ``insert()`` method: | ||
|
||
.. note:: | ||
|
||
This example wraps the dates in the `MongoDB\\BSON\\UTCDateTime <{+phplib-api+}/class.mongodb-bson-utcdatetime.php>`__ | ||
class to convert it to a type MongoDB can serialize because Laravel | ||
skips attribute casting on bulk insert operations. | ||
|
||
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php | ||
:language: php | ||
:dedent: | ||
:start-after: begin model insert many | ||
:end-before: end model insert many | ||
|
||
.. _laravel-fundamentals-modify-documents: | ||
|
||
Modify Documents | ||
---------------- | ||
|
||
In this section, you can learn how to modify documents in your MongoDB | ||
collection from your Laravel application. Use update operations to modify | ||
existing documents or to insert a document if none match the search criteria. | ||
|
||
You can persist changes on an instance of an Eloquent model or use | ||
Eloquent's fluent syntax to chain an update operation on methods that | ||
return a Laravel collection object. | ||
|
||
This section provides examples of the following update operations: | ||
|
||
- :ref:`Update a document <laravel-modify-documents-update-one>` | ||
- :ref:`Update multiple documents <laravel-modify-documents-update-multiple>` | ||
|
||
.. _laravel-modify-documents-update-one: | ||
|
||
Update a Document Examples | ||
~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
||
You can update a document in the following ways: | ||
|
||
- Modify an instance of the model and save the changes by calling the ``save()`` | ||
method. | ||
- Chain methods to retrieve an instance of a model and perform updates on it | ||
by calling the ``update()`` method. | ||
|
||
The following example shows how to update a document by modifying an instance | ||
of the model and calling its ``save()`` method: | ||
|
||
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php | ||
:language: php | ||
:dedent: | ||
:start-after: begin model update one save | ||
:end-before: end model update one save | ||
|
||
When the ``save()`` method succeeds, the model instance on which you called the | ||
method contains the updated values. | ||
|
||
If the operation fails, {+odm-short+} assigns the model instance a null value. | ||
|
||
The following example shows how to update a document by chaining methods to | ||
retrieve and update the first matching document: | ||
|
||
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php | ||
:language: php | ||
:dedent: | ||
:start-after: begin model update one fluent | ||
:end-before: end model update one fluent | ||
|
||
.. note:: | ||
|
||
The ``orderBy()`` call sorts the results by the ``_id`` field to | ||
guarantee a consistent sort order. To learn more about sorting in MongoDB, | ||
see the :manual:`Natural order </reference/glossary/#std-term-natural-order>` | ||
glossary entry in the {+server-docs-name+}. | ||
|
||
When the ``update()`` method succeeds, the operation returns the number of | ||
documents updated. | ||
|
||
If the retrieve part of the call does not match any documents, {+odm-short+} | ||
returns the following error: | ||
|
||
.. code-block:: none | ||
:copyable: false | ||
|
||
Error: Call to a member function update() on null | ||
|
||
.. _laravel-modify-documents-update-multiple: | ||
|
||
Update Multiple Documents Example | ||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
||
To perform an update on one or more documents, chain the ``update()`` | ||
method to the results of a method that retrieves the documents as a | ||
Laravel collection object, such as ``where()``. | ||
|
||
The following example shows how to chain calls to retrieve matching documents | ||
and update them: | ||
|
||
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php | ||
:language: php | ||
:dedent: | ||
:start-after: begin model update multiple | ||
:end-before: end model update multiple | ||
|
||
When the ``update()`` method succeeds, the operation returns the number of | ||
documents updated. | ||
|
||
If the retrieve part of the call does not match any documents in MongoDB, | ||
{+odm-short+} returns the following error: | ||
|
||
.. code-block:: none | ||
:copyable: false | ||
|
||
Error: Call to a member function update() on null | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
<?php | ||
|
||
namespace App\Models; | ||
|
||
use MongoDB\Laravel\Eloquent\Model; | ||
|
||
class Concert extends Model | ||
{ | ||
protected $connection = 'mongodb'; | ||
protected $fillable = ['performer', 'venue', 'genres', 'ticketsSold', 'performanceDate']; | ||
protected $casts = ['performanceDate' => 'datetime']; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
S: not necessary, but I like the detailed description of the code example in lines 86-94. Could be helpful to introduce this code example with more specific info
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there specific info that you think might be helpful to add? I think the insert example adds type information which sets up the rest of the examples on the page, but could be repetitive and draw away from the focus of the rest of the examples.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was thinking of specifying which fields / values you're updating (
venue
,ticketsSold
), but agreed that this could be repetitive and I think it's fine as is!