Skip to content

Commit 70f1b80

Browse files
committed
DOCSP-41967: Insert documents
1 parent bdd0fca commit 70f1b80

File tree

4 files changed

+220
-0
lines changed

4 files changed

+220
-0
lines changed

source/includes/write/insert.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
require 'vendor/autoload.php';
4+
5+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
6+
$client = new MongoDB\Client($uri);
7+
8+
// start-db-coll
9+
$collection = $client->sample_restaurants->restaurants;
10+
// end-db-coll
11+
12+
// Inserts a document that stores a "name" value of "Mongo's Burgers" into the collection
13+
// start-insert-one
14+
$result = $collection->insertOne(['name' => 'Mongo\'s Burgers']);
15+
// end-insert-one
16+
17+
// Inserts documents representing restaurants into the collection
18+
// start-insert-many
19+
$restaurants = [
20+
['name' => 'Mongo\'s Burgers'],
21+
['name' => 'Mongo\'s Pizza']
22+
];
23+
24+
$result = $collection->insertMany($restaurants);
25+
// end-insert-many
26+
27+
// Inserts multiple documents and instructs the insert operation to skip document-level validation
28+
// start-modify
29+
$docs = [
30+
['name' => 'Mongo\'s Burgers'],
31+
['name' => 'Mongo\'s Pizza'],
32+
['name' => 'Mongo\'s Tacos']
33+
];
34+
35+
$result = $collection->insertMany($docs, ['bypassDocumentValidation' => true]);
36+
// end-modify
37+

source/index.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ MongoDB PHP Library
1212

1313
Get Started </get-started>
1414
/read
15+
/write
1516
/tutorial
1617
/upgrade
1718
/reference

source/write.txt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
.. _php-write:
2+
3+
=====================
4+
Write Data to MongoDB
5+
=====================
6+
7+
.. toctree::
8+
:titlesonly:
9+
:maxdepth: 1
10+
11+
/write/insert

source/write/insert.txt

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
.. _php-write-insert:
2+
3+
================
4+
Insert Documents
5+
================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: code example, write, save, create
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+php-library+} to add
24+
documents to a MongoDB collection by performing **insert operations**.
25+
26+
An insert operation inserts one or more documents into a MongoDB collection.
27+
You can perform an insert operation by using the ``MongoDB\Collection::insertOne()``
28+
method to insert a single document or the ``MongoDB\Collection::insertMany()``
29+
method to insert one or more documents.
30+
31+
Sample Data
32+
~~~~~~~~~~~
33+
34+
The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
35+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
36+
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
37+
and assign the following value to your ``collection`` variable:
38+
39+
.. literalinclude:: /includes/read/insert.php
40+
:language: php
41+
:dedent:
42+
:start-after: start-db-coll
43+
:end-before: end-db-coll
44+
45+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
46+
:atlas:`Get Started with Atlas </getting-started>` guide.
47+
48+
The ``_id`` Field
49+
-----------------
50+
51+
In a MongoDB collection, each document *must* contain an ``_id`` field
52+
with a unique field value.
53+
54+
MongoDB allows you to manage this field in two ways:
55+
56+
- You can set this field for each document yourself, ensuring each
57+
``_id`` field value is unique.
58+
- You can let the driver automatically generate unique ``ObjectId``
59+
values for each document ``_id``.
60+
61+
Unless you can guarantee uniqueness, we recommend
62+
letting the driver automatically generate ``_id`` values.
63+
64+
.. note::
65+
66+
Duplicate ``_id`` values violate unique index constraints, which
67+
causes the driver to return a ``MongoDB\Driver\Exception\BulkWriteException``
68+
error.
69+
70+
To learn more about the ``_id`` field, see the
71+
:manual:`Unique Indexes </core/index-unique/>` guide in the {+mdb-server+} manual.
72+
73+
To learn more about document structure and rules, see the
74+
:manual:`Documents </core/document>` guide in the {+mdb-server+} manual.
75+
76+
Insert One Document
77+
-------------------
78+
79+
To add a single document to a MongoDB collection, call the ``MongoDB\Collection::insertOne()``
80+
method and pass the document you want to add.
81+
82+
The following example inserts a document into the ``restaurants`` collection:
83+
84+
.. literalinclude:: /includes/write/insert.php
85+
:language: php
86+
:dedent:
87+
:start-after: start-insert-one
88+
:end-before: end-insert-one
89+
90+
Insert Multiple Documents
91+
-------------------------
92+
93+
To add multiple documents to a MongoDB collection, call the ``MongoDB\Collection::insertMany()``
94+
method and pass an array that stores the documents you want to add.
95+
96+
The following example inserts two documents into the ``restaurants`` collection:
97+
98+
.. literalinclude:: /includes/write/insert.php
99+
:language: php
100+
:dedent:
101+
:start-after: start-insert-many
102+
:end-before: end-insert-many
103+
104+
Modify Insert Behavior
105+
----------------------
106+
107+
You can modify the behavior of the ``MongoDB\Collection::insertOne()`` and
108+
``MongoDB\Collection::insertMany()`` methods by passing an array that specifies
109+
option values as a parameter. The following table describes some options
110+
you can set in the array:
111+
112+
.. list-table::
113+
:widths: 30 70
114+
:header-rows: 1
115+
116+
* - Field
117+
- Description
118+
119+
* - ``bypassDocumentValidation``
120+
- | If set to ``true``, allows the write to opt out of
121+
:manual:`document-level validation </core/schema-validation>`.
122+
| Defaults to ``false``.
123+
| **Type**: ``bool``
124+
125+
* - ``writeConcern``
126+
- | Sets the write concern for the operation.
127+
| Defaults to the write concern of the namespace.
128+
| **Type**: ``MongoDB\Driver\WriteConcern``
129+
130+
* - ``ordered``
131+
- | If set to ``true``, the operation stops inserting documents when one insert
132+
fails. If ``false``, the operation continues to insert the remaining documents
133+
when one insert fails. You cannot pass this option to the ``insertOne()`` method.
134+
| Defaults to ``true``.
135+
| **Type**: ``bool``
136+
137+
* - ``comment``
138+
- | A comment to attach to the operation. For more information, see the :manual:`insert command
139+
fields </reference/command/insert/#command-fields>` guide in the
140+
{+mdb-server+} manual.
141+
| **Type**: any valid BSON type
142+
143+
Example
144+
~~~~~~~
145+
146+
The following code uses the ``insertMany()`` method to insert three new
147+
documents into a collection. Because the ``bypassDocumentValidation`` field
148+
is set to ``true`` in an options array, this
149+
insert operation bypasses document-level validation:
150+
151+
.. literalinclude:: /includes/write/insert.php
152+
:language: php
153+
:dedent:
154+
:start-after: start-modify
155+
:end-before: end-modify
156+
157+
Additional Information
158+
----------------------
159+
160+
.. TODO:
161+
For runnable code examples of inserting documents with the {+php-library+}, see
162+
:ref:`php-write`.
163+
164+
API Documentation
165+
~~~~~~~~~~~~~~~~~
166+
167+
To learn more about any of the methods or types discussed in this
168+
guide, see the following API documentation:
169+
170+
- `MongoDB\\Collection::insertOne() <{+api+}/method/MongoDBCollection-insertOne/>`__
171+
- `MongoDB\\Collection::insertMany() <{+api+}/method/MongoDBCollection-insertMany/>`__

0 commit comments

Comments
 (0)