-
Notifications
You must be signed in to change notification settings - Fork 1.5k
DOCSP-35948 write operations - insert documents #2804
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
Changes from 9 commits
8fbbcc4
a5a75ca
a678179
eea96e5
88024a5
24fdd13
77bdbec
831f06e
d813f23
9fcce6f
3c04080
e8c1491
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
.. _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 perform the following tasks by using the {+odm-long+} in the | ||
following pages: | ||
|
||
- :ref:`Read Operations <laravel-fundamentals-read-ops>` | ||
- :ref:`Write Operations <laravel-fundamentals-write-ops>` | ||
|
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,139 @@ | ||||||
.. _laravel-fundamentals-write-ops: | ||||||
|
||||||
================ | ||||||
Write Operations | ||||||
================ | ||||||
|
||||||
.. facet:: | ||||||
:name: genre | ||||||
:values: tutorial | ||||||
|
||||||
.. meta:: | ||||||
:keywords: insert, insert one, update, update one, upsert, delete, delete many, 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` | ||||||
- Modify Documents | ||||||
- Delete Documents | ||||||
Comment on lines
+30
to
+31
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note to reviewer: |
||||||
|
||||||
.. _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` guide. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: since this links to a section of the "Schema Builder" guide and not a separate "Indexes" guide, I think something like this would be more accurate:
Suggested change
|
||||||
|
||||||
This section uses the following example model class to demonstrate how to | ||||||
use Eloquent models to perform insert operations: | ||||||
|
||||||
.. 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`. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: I'd clarify where this links to
Suggested change
|
||||||
|
||||||
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. | ||||||
|
||||||
To learn more about Eloquent models in {+odm-short+} see the :ref:`laravel-eloquent-models` | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: add a comma here
Suggested change
|
||||||
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, the instance on which you called the | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: since you mention a Concert model instance in the previous paragraph, I think the use of "instance" here is a little confusing. It would be helpful to clarify that this refers to a MongoDB instance:
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch! This is the model instance, so I'll clarify that. |
||||||
method contains the model. If it fails, the 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`` field | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: [nit] I think field should be plural
Suggested change
|
||||||
- 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 | ||||||
`Carbon <https://github.com/briannesbitt/Carbon>`__ GitHub repository. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: you can use :github: here
Suggested change
|
||||||
|
||||||
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 ``insert()`` method: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: add "the"
Suggested change
|
||||||
|
||||||
.. 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 | ||||||
|
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', 'performanceDate']; | ||
protected $casts = ['performanceDate' => 'datetime']; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace App\Http\Controllers; | ||
|
||
use App\Models\Concert; | ||
use Carbon\Carbon; | ||
use MongoDB\BSON\UTCDateTime; | ||
use MongoDB\Laravel\Tests\TestCase; | ||
|
||
use function count; | ||
|
||
class WriteOperationsTest extends TestCase | ||
{ | ||
/** | ||
* @runInSeparateProcess | ||
* @preserveGlobalState disabled | ||
*/ | ||
public function testModelInsert(): void | ||
{ | ||
// <optionally, add code here to clean the database/collection> | ||
|
||
require_once __DIR__ . '/Concert.php'; | ||
|
||
Concert::truncate(); | ||
|
||
// begin model insert one | ||
$concert = new Concert(); | ||
$concert->performer = 'Mitsuko Uchida'; | ||
$concert->venue = 'Carnegie Hall'; | ||
$concert->performanceDate = Carbon::create(2024, 4, 1, 20, 0, 0, 'EST'); | ||
$concert->save(); | ||
// end model insert one | ||
|
||
// begin inserted id | ||
$insertedId = $concert->id; | ||
// end inserted id | ||
|
||
$this->assertNotNull($concert); | ||
$this->assertNotNull($insertedId); | ||
|
||
$result = Concert::first(); | ||
$this->assertInstanceOf(Concert::class, $result); | ||
} | ||
|
||
/** | ||
* @runInSeparateProcess | ||
* @preserveGlobalState disabled | ||
*/ | ||
public function testModelInsertMassAssign(): void | ||
{ | ||
// <optionally, add code here to clean the database/collection> | ||
|
||
require_once __DIR__ . '/Concert.php'; | ||
|
||
Concert::truncate(); | ||
|
||
// begin model insert one mass assign | ||
$insertResult = Concert::create([ | ||
'performer' => 'The Rolling Stones', | ||
'venue' => 'Soldier Field', | ||
'performanceDate' => Carbon::create(2024, 6, 30, 20, 0, 0, 'CDT'), | ||
]); | ||
// end model insert one mass assign | ||
|
||
$this->assertNotNull($insertResult); | ||
|
||
$result = Concert::first(); | ||
$this->assertInstanceOf(Concert::class, $result); | ||
} | ||
|
||
/** | ||
* @runInSeparateProcess | ||
* @preserveGlobalState disabled | ||
*/ | ||
public function testModelInsertMany(): void | ||
{ | ||
// <optionally, add code here to clean the database/collection> | ||
GromNaN marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
require_once __DIR__ . '/Concert.php'; | ||
|
||
Concert::truncate(); | ||
|
||
// begin model insert many | ||
$data = [ | ||
[ | ||
'performer' => 'Brad Mehldau', | ||
'venue' => 'Philharmonie de Paris', | ||
'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')), | ||
], | ||
[ | ||
'performer' => 'Billy Joel', | ||
'venue' => 'Madison Square Garden', | ||
'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')), | ||
], | ||
]; | ||
|
||
Concert::insert($data); | ||
// end model insert many | ||
|
||
$results = Concert::get(); | ||
|
||
$this->assertEquals(2, count($results)); | ||
} | ||
} |
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: this sentence is a little repetitive; you could reword to something like:
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.
Thanks, I like this reworded version!