Skip to content

Commit 4459b55

Browse files
author
Chris Cho
authored
DOCSP-35948 write operations - insert documents (#2804)
* DOCSP-35948: Write operations
1 parent 260620e commit 4459b55

File tree

6 files changed

+286
-5
lines changed

6 files changed

+286
-5
lines changed

docs/fundamentals.txt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
.. _laravel_fundamentals:
2+
3+
============
4+
Fundamentals
5+
============
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: php framework, odm
13+
14+
.. toctree::
15+
:titlesonly:
16+
:maxdepth: 1
17+
18+
/fundamentals/read-operations
19+
/fundamentals/write-operations
20+
21+
Learn how to use the {+odm-long+} to perform the following tasks:
22+
23+
- :ref:`Read Operations <laravel-fundamentals-read-ops>`
24+
- :ref:`Write Operations <laravel-fundamentals-write-ops>`
25+

docs/retrieve.txt renamed to docs/fundamentals/read-operations.txt

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
.. _laravel-fundamentals-retrieve:
2+
.. _laravel-fundamentals-read-ops:
23

3-
==============
4-
Retrieve Data
5-
==============
4+
===============
5+
Read Operations
6+
===============
67

78
.. facet::
89
:name: genre
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
.. _laravel-fundamentals-write-ops:
2+
3+
================
4+
Write Operations
5+
================
6+
7+
.. facet::
8+
:name: genre
9+
:values: tutorial
10+
11+
.. meta::
12+
:keywords: insert, insert one, update, update one, upsert, delete, delete many, code example, mass assignment, eloquent model
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use {+odm-short+} to perform
24+
**write operations** on your MongoDB collections. Write operations include
25+
inserting, updating, and deleting data based on specified criteria.
26+
27+
This guide shows you how to perform the following tasks:
28+
29+
- :ref:`laravel-fundamentals-insert-documents`
30+
- Modify Documents
31+
- Delete Documents
32+
33+
.. _laravel-fundamentals-insert-documents:
34+
35+
Insert Documents
36+
----------------
37+
38+
In this section, you can learn how to insert documents into MongoDB collections
39+
from your Laravel application by using the {+odm-long+}.
40+
41+
When you insert the documents, ensure the data does not violate any
42+
unique indexes on the collection. When inserting the first document of a
43+
collection or creating a new collection, MongoDB automatically creates a
44+
unique index on the ``_id`` field.
45+
46+
For more information on creating indexes on MongoDB collections by using the
47+
Laravel schema builder, see the :ref:`laravel-eloquent-indexes` section
48+
of the Schema Builder documentation.
49+
50+
This section uses the following example model class to demonstrate how to
51+
use Eloquent models to perform insert operations:
52+
53+
.. literalinclude:: /includes/fundamentals/write-operations/Concert.php
54+
:language: php
55+
:dedent:
56+
:caption: Concert.php
57+
58+
.. tip::
59+
60+
The ``$fillable`` attribute lets you use Laravel mass assignment for insert
61+
operations. To learn more about mass assignment, see :ref:`laravel-model-mass-assignment`
62+
in the Eloquent Model Class documentation.
63+
64+
The ``$casts`` attribute instructs Laravel to convert attributes to common
65+
data types. To learn more, see `Attribute Casting <https://laravel.com/docs/{+laravel-docs-version+}/eloquent-mutators#attribute-casting>`__
66+
in the Laravel documentation.
67+
68+
To learn more about Eloquent models in {+odm-short+}, see the :ref:`laravel-eloquent-models`
69+
section.
70+
71+
Insert a Document Examples
72+
~~~~~~~~~~~~~~~~~~~~~~~~~~
73+
74+
These examples show how to use the ``save()`` Eloquent method to insert an
75+
instance of a ``Concert`` model as a MongoDB document.
76+
77+
When the ``save()`` method succeeds, you can access the model instance on
78+
which you called the method. If the operation fails, the model instance is
79+
assigned ``null``.
80+
81+
This example code performs the following actions:
82+
83+
- Creates a new instance of the ``Concert`` model
84+
- Assigns string values to the ``performer`` and ``venue`` fields
85+
- Assigns a date to the ``performanceDate`` field by using the ``Carbon``
86+
package
87+
- Inserts the document by calling the ``save()`` method
88+
89+
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php
90+
:language: php
91+
:dedent:
92+
:start-after: begin model insert one
93+
:end-before: end model insert one
94+
95+
You can retrieve the inserted document's ``_id`` value by accessing the model's
96+
``id`` member as shown in the following code example:
97+
98+
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php
99+
:language: php
100+
:dedent:
101+
:start-after: begin inserted id
102+
:end-before: end inserted id
103+
104+
If you enable mass assignment by defining either the ``$fillable`` or
105+
``$guarded`` attributes, you can use the Eloquent model ``create()`` method
106+
to perform the insert in a single call as shown in the following example:
107+
108+
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php
109+
:language: php
110+
:dedent:
111+
:start-after: begin model insert one mass assign
112+
:end-before: end model insert one mass assign
113+
114+
To learn more about the Carbon PHP API extension, see the
115+
:github:`Carbon <briannesbitt/Carbon>` GitHub repository.
116+
117+
Insert Multiple Documents Example
118+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119+
120+
This example shows how to use the ``insert()`` Eloquent method to insert
121+
multiple instances of a ``Concert`` model as MongoDB documents. This bulk
122+
insert method reduces the number of calls your application needs to make
123+
to save the documents.
124+
125+
When the ``insert()`` method succeeds, it returns the value ``1``. If it
126+
fails, it throws an exception.
127+
128+
The example code saves multiple models in a single call by passing them as
129+
an array to the ``insert()`` method:
130+
131+
.. note::
132+
133+
This example wraps the dates in the `MongoDB\BSON\UTCDateTime <{+phplib-api+}/class.mongodb-bson-utcdatetime.php>`__
134+
class to convert it to a type MongoDB can serialize because Laravel
135+
skips attribute casting on bulk insert operations.
136+
137+
.. literalinclude:: /includes/fundamentals/write-operations/WriteOperationsTest.php
138+
:language: php
139+
:dedent:
140+
:start-after: begin model insert many
141+
:end-before: end model insert many
142+
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
namespace App\Models;
4+
5+
use MongoDB\Laravel\Eloquent\Model;
6+
7+
class Concert extends Model
8+
{
9+
protected $connection = 'mongodb';
10+
protected $fillable = ['performer', 'venue', 'performanceDate'];
11+
protected $casts = ['performanceDate' => 'datetime'];
12+
}
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace App\Http\Controllers;
6+
7+
use App\Models\Concert;
8+
use Carbon\Carbon;
9+
use MongoDB\BSON\UTCDateTime;
10+
use MongoDB\Laravel\Tests\TestCase;
11+
12+
use function count;
13+
14+
class WriteOperationsTest extends TestCase
15+
{
16+
/**
17+
* @runInSeparateProcess
18+
* @preserveGlobalState disabled
19+
*/
20+
public function testModelInsert(): void
21+
{
22+
require_once __DIR__ . '/Concert.php';
23+
24+
Concert::truncate();
25+
26+
// begin model insert one
27+
$concert = new Concert();
28+
$concert->performer = 'Mitsuko Uchida';
29+
$concert->venue = 'Carnegie Hall';
30+
$concert->performanceDate = Carbon::create(2024, 4, 1, 20, 0, 0, 'EST');
31+
$concert->save();
32+
// end model insert one
33+
34+
// begin inserted id
35+
$insertedId = $concert->id;
36+
// end inserted id
37+
38+
$this->assertNotNull($concert);
39+
$this->assertNotNull($insertedId);
40+
41+
$result = Concert::first();
42+
$this->assertInstanceOf(Concert::class, $result);
43+
}
44+
45+
/**
46+
* @runInSeparateProcess
47+
* @preserveGlobalState disabled
48+
*/
49+
public function testModelInsertMassAssign(): void
50+
{
51+
require_once __DIR__ . '/Concert.php';
52+
53+
Concert::truncate();
54+
55+
// begin model insert one mass assign
56+
$insertResult = Concert::create([
57+
'performer' => 'The Rolling Stones',
58+
'venue' => 'Soldier Field',
59+
'performanceDate' => Carbon::create(2024, 6, 30, 20, 0, 0, 'CDT'),
60+
]);
61+
// end model insert one mass assign
62+
63+
$this->assertNotNull($insertResult);
64+
65+
$result = Concert::first();
66+
$this->assertInstanceOf(Concert::class, $result);
67+
}
68+
69+
/**
70+
* @runInSeparateProcess
71+
* @preserveGlobalState disabled
72+
*/
73+
public function testModelInsertMany(): void
74+
{
75+
require_once __DIR__ . '/Concert.php';
76+
77+
Concert::truncate();
78+
79+
// begin model insert many
80+
$data = [
81+
[
82+
'performer' => 'Brad Mehldau',
83+
'venue' => 'Philharmonie de Paris',
84+
'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')),
85+
],
86+
[
87+
'performer' => 'Billy Joel',
88+
'venue' => 'Madison Square Garden',
89+
'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')),
90+
],
91+
];
92+
93+
Concert::insert($data);
94+
// end model insert many
95+
96+
$results = Concert::get();
97+
98+
$this->assertEquals(2, count($results));
99+
}
100+
}

docs/index.txt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Laravel MongoDB
1515

1616
/quick-start
1717
Release Notes <https://github.com/mongodb/laravel-mongodb/releases/>
18-
/retrieve
18+
/fundamentals
1919
/eloquent-models
2020
/query-builder
2121
/user-authentication
@@ -53,7 +53,8 @@ Fundamentals
5353
To learn how to perform the following tasks by using the {+odm-short+},
5454
see the following content:
5555

56-
- :ref:`laravel-fundamentals-retrieve`
56+
- :ref:`laravel-fundamentals-read-ops`
57+
- :ref:`laravel-fundamentals-write-ops`
5758
- :ref:`laravel-eloquent-models`
5859
- :ref:`laravel-query-builder`
5960
- :ref:`laravel-user-authentication`

0 commit comments

Comments
 (0)