Commit 56be18e1 authored by Jeremy Mikola's avatar Jeremy Mikola

Revise tutorial articles

parent 11b6a695
...@@ -13,11 +13,12 @@ Execute Database Commands ...@@ -13,11 +13,12 @@ Execute Database Commands
Overview Overview
-------- --------
The |php-library| provides :ref:`helper methods <database-methods>` The |php-library| provides helper methods across the :phpclass:`Client
for common :manual:`database commands </reference/command>`. In <MongoDB\\Client>`, :phpclass:`Database <MongoDB\\Database>`, and
addition, the |php-library| provides the :phpclass:`Collection <MongoDB\\Collection>` classes for common
:phpmethod:`MongoDB\\Database::command` method to run database commands :manual:`database commands </reference/command>`. In addition, the
with PHP that do not have helper methods. :phpmethod:`MongoDB\\Database::command()` method may be used to run database
commands that do not have a helper method.
Execute Database Commands Execute Database Commands
------------------------- -------------------------
...@@ -26,12 +27,10 @@ Basic Command ...@@ -26,12 +27,10 @@ Basic Command
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
To execute a command on a :program:`mongod` instance, use the To execute a command on a :program:`mongod` instance, use the
:phpmethod:`MongoDB\\Database::command` method. For instance, the :phpmethod:`MongoDB\\Database::command()` method. For instance, the following
following operation uses the :dbcommand:`geoNear` HERE command to search for operation uses the :manual:`geoNear </reference/command/geoNear>` command to
the three closest documents to longitude ``-74`` and latitude ``40`` in search for the three closest documents to longitude ``-74`` and latitude ``40``
the ``restos`` collection in the ``example`` database: in the ``restos`` collection in the ``example`` database:
:readmode:`secondary`
.. code-block:: php .. code-block:: php
...@@ -39,249 +38,188 @@ the ``restos`` collection in the ``example`` database: ...@@ -39,249 +38,188 @@ the ``restos`` collection in the ``example`` database:
$database = (new MongoDB\Client)->example; $database = (new MongoDB\Client)->example;
$results = $database->command( $cursor = $database->command([
[
'geoNear' => 'restos', 'geoNear' => 'restos',
'near' => [ 'near' => [
'type' => 'Point', 'type' => 'Point',
'coordinates' => [-74.0, 40.0] 'coordinates' => [-74.0, 40.0],
], ],
'spherical' => 'true', 'spherical' => 'true',
'num' => 3 'num' => 3,
] ]);
);
$results = $cursor->toArray()[0];
var_dump($results); var_dump($results);
The output would resemble:: The output would then resemble::
object(MongoDB\Driver\Cursor)#10 (2) { object(MongoDB\Model\BSONDocument)#27 (1) {
["cursor"]=> ["storage":"ArrayObject":private]=>
array(17) { array(4) {
["stamp"]=>
int(0)
["is_command"]=>
bool(true)
["sent"]=>
bool(true)
["done"]=>
bool(false)
["end_of_event"]=>
bool(false)
["in_exhaust"]=>
bool(false)
["has_fields"]=>
bool(false)
["query"]=>
object(stdClass)#3 (4) {
["geoNear"]=>
string(6) "restos"
["near"]=>
object(stdClass)#9 (2) {
["type"]=>
string(5) "Point"
["coordinates"]=>
array(2) {
[0]=>
float(-74)
[1]=>
float(40)
}
}
["spherical"]=>
string(4) "true"
["num"]=>
int(3)
}
["fields"]=>
object(stdClass)#8 (0) {
}
["read_preference"]=>
array(2) {
["mode"]=>
int(1)
["tags"]=>
array(0) {
}
}
["flags"]=>
int(0)
["skip"]=>
int(0)
["limit"]=>
int(1)
["count"]=>
int(1)
["batch_size"]=>
int(0)
["ns"]=>
string(12) "example.$cmd"
["current_doc"]=>
object(stdClass)#24 (4) {
["waitedMS"]=> ["waitedMS"]=>
int(0) int(0)
["results"]=> ["results"]=>
object(MongoDB\Model\BSONArray)#25 (1) {
["storage":"ArrayObject":private]=>
array(3) { array(3) {
[0]=> [0]=>
object(stdClass)#14 (2) { object(MongoDB\Model\BSONDocument)#14 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dis"]=> ["dis"]=>
float(66308.6190421) float(39463.618389163)
["obj"]=> ["obj"]=>
object(stdClass)#13 (5) { object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["_id"]=> ["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) { object(MongoDB\BSON\ObjectID)#3 (1) {
["oid"]=> ["oid"]=>
string(24) "57506d62f57802807471dd28" string(24) "55cba2486c522cafdb059bed"
} }
["name"]=>
string(21) "XYZ Bagels Restaurant"
["contact"]=>
object(stdClass)#12 (3) {
["phone"]=>
string(12) "435-555-0190"
["email"]=>
string(31) "XYZBagelsRestaurant@example.net"
["location"]=> ["location"]=>
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["coordinates"]=>
object(MongoDB\Model\BSONArray)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) { array(2) {
[0]=> [0]=>
float(-74.0707363) float(-74.1641319)
[1]=> [1]=>
float(40.5932157) float(39.6686512)
} }
} }
["stars"]=> ["type"]=>
int(4) string(5) "Point"
["categories"]=> }
array(3) { }
[0]=> ["name"]=>
string(6) "Bagels" string(32) "Soul Food Kitchen Seafood Heaven"
[1]=> }
string(10) "Sandwiches"
[2]=>
string(6) "Coffee"
} }
} }
} }
[1]=> [1]=>
object(stdClass)#18 (2) { object(MongoDB\Model\BSONDocument)#19 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dis"]=> ["dis"]=>
float(69014.6014737) float(50686.851650416)
["obj"]=> ["obj"]=>
object(stdClass)#17 (5) { object(MongoDB\Model\BSONDocument)#18 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["_id"]=> ["_id"]=>
object(MongoDB\BSON\ObjectID)#15 (1) { object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=> ["oid"]=>
string(24) "57506d62f57802807471dd39" string(24) "55cba2476c522cafdb0544df"
} }
["name"]=>
string(20) "Green Feast Pizzeria"
["contact"]=>
object(stdClass)#16 (3) {
["phone"]=>
string(12) "840-555-0102"
["email"]=>
string(30) "GreenFeastPizzeria@example.com"
["location"]=> ["location"]=>
object(MongoDB\Model\BSONDocument)#17 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["coordinates"]=>
object(MongoDB\Model\BSONArray)#16 (1) {
["storage":"ArrayObject":private]=>
array(2) { array(2) {
[0]=> [0]=>
float(-74.1220973) float(-74.2566332)
[1]=> [1]=>
float(40.6129407) float(40.4109872)
} }
} }
["stars"]=> ["type"]=>
int(2) string(5) "Point"
["categories"]=> }
array(2) { }
[0]=> ["name"]=>
string(5) "Pizza" string(20) "Seguine Bagel Bakery"
[1]=> }
string(7) "Italian"
} }
} }
} }
[2]=> [2]=>
object(stdClass)#22 (2) { object(MongoDB\Model\BSONDocument)#24 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dis"]=> ["dis"]=>
float(69975.5031089) float(58398.379630263)
["obj"]=> ["obj"]=>
object(stdClass)#21 (5) { object(MongoDB\Model\BSONDocument)#23 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["_id"]=> ["_id"]=>
object(MongoDB\BSON\ObjectID)#19 (1) { object(MongoDB\BSON\ObjectID)#20 (1) {
["oid"]=> ["oid"]=>
string(24) "57506d62f57802807471dd35" string(24) "55cba2476c522cafdb053c92"
} }
["name"]=>
string(14) "XYZ Coffee Bar"
["contact"]=>
object(stdClass)#20 (3) {
["phone"]=>
string(12) "644-555-0193"
["email"]=>
string(24) "XYZCoffeeBar@example.net"
["location"]=> ["location"]=>
object(MongoDB\Model\BSONDocument)#22 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["coordinates"]=>
object(MongoDB\Model\BSONArray)#21 (1) {
["storage":"ArrayObject":private]=>
array(2) { array(2) {
[0]=> [0]=>
float(-74.0166091) float(-74.3731727)
[1]=> [1]=>
float(40.6284767) float(40.4404759)
}
}
["type"]=>
string(5) "Point"
}
}
["name"]=>
string(17) "Water'S Edge Club"
} }
} }
["stars"]=>
int(5)
["categories"]=>
array(4) {
[0]=>
string(6) "Coffee"
[1]=>
string(4) "Cafe"
[2]=>
string(6) "Bakery"
[3]=>
string(10) "Chocolates"
} }
} }
} }
} }
["stats"]=> ["stats"]=>
object(stdClass)#23 (5) { object(MongoDB\Model\BSONDocument)#26 (1) {
["storage":"ArrayObject":private]=>
array(5) {
["nscanned"]=> ["nscanned"]=>
int(11) int(25139)
["objectsLoaded"]=> ["objectsLoaded"]=>
int(10) int(25134)
["avgDistance"]=> ["avgDistance"]=>
float(68432.9078749) float(49516.283223281)
["maxDistance"]=> ["maxDistance"]=>
float(69975.5031089) float(58398.379630263)
["time"]=> ["time"]=>
int(0) int(126)
}
} }
["ok"]=> ["ok"]=>
float(1) float(1)
} }
} }
["server_id"]=>
int(1)
}
Commands with Custom Read Preference Commands with Custom Read Preference
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some commands, such as :manual:`createUser Some commands, such as :manual:`createUser </reference/command/createUser/>`,
</reference/command/createUser/>`, may only be executed on a may only be executed on a :term:`primary` replica set member or a
:term:`primary` replica set member or a :term:`standalone`. :term:`standalone`.
The command helper methods in the The command helper methods in the |php-library|, such as
|php-library|, such as :phpmethod:`MongoDB\\Database::drop`, :phpmethod:`MongoDB\\Database::drop()`, know to apply their own :term:`read
know to apply their own :term:`read preference` if necessary. However, preference` if necessary. However, the :phpmethod:`MongoDB\\Database::command()`
the :phpmethod:`MongoDB\\Database::command` method is a generic method and method is a generic method and defaults to the read preference of the Database
defaults to the read preference of the object on which it is invoked. To execute commands that require a specific read
Database object on which it is invoked. To execute commands that require preference, specify the read preference in the ``$options`` parameter of the
specific read preference, specify the read preference in the ``$options`` method.
parameter of the method.
The following example adds a user to the ``demo`` database The following example adds a user to the ``demo`` database and specifies a
and specifies a custom read preference: custom read preference:
.. code-block:: php .. code-block:: php
...@@ -321,10 +259,9 @@ View Single Result Documents ...@@ -321,10 +259,9 @@ View Single Result Documents
The :phpmethod:`MongoDB\\Database::command()` method returns a The :phpmethod:`MongoDB\\Database::command()` method returns a
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object. :php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object.
Many MongoDB commands return their responses as a single document in an Many MongoDB commands return their responses as a single document. To read the
array. To read the command response, you may either iterate on the command response, you may either iterate on the cursor and access the first
cursor and access the first document, or access the first result in the document, or access the first result in the array, as in the following:
array, as in the following:
.. code-block:: php .. code-block:: php
...@@ -350,13 +287,12 @@ Iterate Results from a Cursor ...@@ -350,13 +287,12 @@ Iterate Results from a Cursor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some commands, such as :manual:`listCollections Some commands, such as :manual:`listCollections
</reference/command/listCollections/>`, </reference/command/listCollections/>`, return their results via an iterable
return their results via an iterable cursor. To view the results, cursor. To view the results, iterate through the cursor.
iterate through the cursor.
The following example lists the collections in the ``demo`` database by The following example lists the collections in the ``demo`` database by
iterating through the cursor returned by the ``listCollections`` command iterating through the cursor returned by the ``listCollections`` command using a
using a ``foreach`` loop: ``foreach`` loop:
.. code-block:: php .. code-block:: php
...@@ -370,8 +306,8 @@ using a ``foreach`` loop: ...@@ -370,8 +306,8 @@ using a ``foreach`` loop:
echo $collection['name'], "\n"; echo $collection['name'], "\n";
} }
The output would then be a list of the values for the ``name`` key, The output would then be a list of the values for the ``name`` key, for
for instance:: instance::
persons persons
posts posts
...@@ -379,10 +315,11 @@ for instance:: ...@@ -379,10 +315,11 @@ for instance::
.. note:: .. note::
At the *protocol* level, commands that support a cursor At the *protocol* level, commands that support a cursor return a single
return a single result document with the essential ingredients for result document with the essential ingredients for constructing the command
constructing the command cursor (i.e. the cursor's ID, namespace, and cursor (i.e. the cursor's ID, namespace, and the first batch of results). In
the first batch of results). In the PHP driver implementation, the the PHP driver implementation, the
:php:`executeCommand() <mongodb-driver-manager.executecommand>` :php:`MongoDB\Driver\Manager::executeCommand()
method detects the single result and constructs the iterable command <mongodb-driver-manager.executecommand>` method detects such a result and
cursor, which is returned rather than the base result document. constructs the iterable command cursor, which is returned rather than the
base result document.
...@@ -12,16 +12,16 @@ CRUD Operations ...@@ -12,16 +12,16 @@ CRUD Operations
CRUD operations *create*, *read*, *update*, and *delete* documents. The CRUD operations *create*, *read*, *update*, and *delete* documents. The
|php-library|'s :phpclass:`MongoDB\\Collection` class implements |php-library|'s :phpclass:`MongoDB\\Collection` class implements MongoDB's
MongoDB's cross-driver `CRUD specification cross-driver `CRUD specification
<https://github.com/mongodb/specifications/blob/master/source/crud/crud. <https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst>`_,
rst>`_, providing access to methods for inserting, finding, updating, providing access to methods for inserting, finding, updating, and deleting
and deleting documents in MongoDB. documents in MongoDB.
This document provides a general introduction to inserting, querying, This document provides a general introduction to inserting, querying, updating,
updating, and deleting documents using the |php-library|. The MongoDB and deleting documents using the |php-library|. The MongoDB Manual's
Manual's :manual:`CRUD Section </crud>` provides a more thorough :manual:`CRUD Section </crud>` provides a more thorough introduction to CRUD
introduction to CRUD operations with MongoDB. operations with MongoDB.
Insert Documents Insert Documents
---------------- ----------------
...@@ -29,11 +29,12 @@ Insert Documents ...@@ -29,11 +29,12 @@ Insert Documents
Insert One Document Insert One Document
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::insertOne` method inserts a single The :phpmethod:`MongoDB\\Collection::insertOne()` method inserts a single
document into MongoDB and returns an instance of ``MongoDB\InsertOneResult``, document into MongoDB and returns an instance of
which you can use to access the IDs of the inserted document. :phpclass:`MongoDB\\InsertOneResult`, which you can use to access the ID of the
inserted document.
.. this uses the insertMany example from the method reference: .. this uses the insertOne example from the method reference:
.. include:: /reference/method/MongoDBCollection-insertOne.txt .. include:: /reference/method/MongoDBCollection-insertOne.txt
:start-after: start-crud-include :start-after: start-crud-include
...@@ -41,12 +42,12 @@ which you can use to access the IDs of the inserted document. ...@@ -41,12 +42,12 @@ which you can use to access the IDs of the inserted document.
The output includes the ID of the inserted document. The output includes the ID of the inserted document.
If you include an ``_id`` value when inserting a document, MongoDB checks If you include an ``_id`` value when inserting a document, MongoDB checks to
to ensure that the ``_id`` value is unique for the collection. If the ensure that the ``_id`` value is unique for the collection. If the ``_id`` value
``_id`` value is not unique, the insert operation fails due to a duplicate is not unique, the insert operation fails due to a duplicate key error.
key error.
The following example inserts a document while specifying the value for the ``_id``: The following example inserts a document while specifying the value for the
``_id``:
.. code-block:: php .. code-block:: php
...@@ -65,15 +66,15 @@ The output would then resemble:: ...@@ -65,15 +66,15 @@ The output would then resemble::
Inserted 1 document(s) Inserted 1 document(s)
int(1) int(1)
.. seealso:: :phpmethod:`MongoDB\\Collection::insertOne` reference. .. seealso:: :phpmethod:`MongoDB\\Collection::insertOne()`
Insert Many Documents Insert Many Documents
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::insertMany` method allows you to The :phpmethod:`MongoDB\\Collection::insertMany()` method allows you to insert
insert multiple documents in one write operation and returns an instance multiple documents in one write operation and returns an instance of
of ``MongoDB\InsertManyResult``, which you can use to access the :phpclass:`MongoDB\\InsertManyResult`, which you can use to access the IDs of
IDs of the inserted documents. the inserted documents.
.. this uses the insertMany example from the method reference: .. this uses the insertMany example from the method reference:
...@@ -81,25 +82,24 @@ IDs of the inserted documents. ...@@ -81,25 +82,24 @@ IDs of the inserted documents.
:start-after: start-crud-include :start-after: start-crud-include
:end-before: end-crud-include :end-before: end-crud-include
.. seealso:: :phpmethod:`MongoDB\\Collection::insertMany` reference. .. seealso:: :phpmethod:`MongoDB\\Collection::insertMany()`
Query Documents Query Documents
--------------- ---------------
The |php-library| provides the :phpmethod:`MongoDB\\Collection::findOne` The |php-library| provides the :phpmethod:`MongoDB\\Collection::findOne()` and
and :phpmethod:`MongoDB\\Collection:findMany` methods for querying :phpmethod:`MongoDB\\Collection::find()` methods for querying documents and the
documents and the :phpmethod:`MongoDB\\Collection:aggregate` :phpmethod:`MongoDB\\Collection::aggregate()` method for performing
method for performing :manual:`aggregation operations :manual:`aggregation operations </core/aggregation-pipeline>`.
</core/aggregation-pipeline`.
Find One Document Find One Document
~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::findOne` returns the :term:`first :phpmethod:`MongoDB\\Collection::findOne()` returns the :term:`first document
document <natural order>` that matches the query or ``null`` if no <natural order>` that matches the query or ``null`` if no document matches the
document matches the query. query.
The following example searches for the document with ``_id: 94301``: The following example searches for the document with ``_id`` of ``"94301"``:
.. code-block:: php .. code-block:: php
...@@ -137,17 +137,17 @@ The output would then resemble:: ...@@ -137,17 +137,17 @@ The output would then resemble::
} }
} }
.. seealso:: :phpmethod:`MongoDB\\Collection::findMany` reference .. seealso:: :phpmethod:`MongoDB\\Collection::findOne()`
Find Many Documents Find Many Documents
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::find` returns a :phpmethod:`MongoDB\\Collection::find()` returns a
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object, which you :php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object, which you can
can iterate upon to access all matched documents. iterate upon to access all matched documents.
The following example lists the documents in the ``zips`` collection The following example lists the documents in the ``zips`` collection with the
with the specified city and state values: specified city and state values:
.. code-block:: php .. code-block:: php
...@@ -170,46 +170,50 @@ The output would resemble:: ...@@ -170,46 +170,50 @@ The output would resemble::
07307 07307
07310 07310
.. seealso:: :phpmethod:`MongoDB\\Collection::find` reference .. seealso:: :phpmethod:`MongoDB\\Collection::find()`
.. _php-query-projection: .. _php-query-projection:
Query Projection Query Projection
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
By default, queries in MongoDB return all fields in matching documents. By default, queries in MongoDB return all fields in matching documents. To limit
To limit the amount of data that MongoDB sends to applications, you can the amount of data that MongoDB sends to applications, you can include a
include a :manual:`projection document :manual:`projection document </tutorial/project-fields-from-query-results>` in
</tutorial/project-fields-from-query-results>` in the query operation. the query operation.
.. note:: .. note::
MongoDB includes the ``_id`` field by default unless you explicitly MongoDB includes the ``_id`` field by default unless you explicitly exclude
exclude it in a projection document. it in a projection document.
The following example finds restaurants based on the ``cuisine`` and The following example finds restaurants based on the ``cuisine`` and ``borough``
``borough`` fields and uses a :manual:`projection fields and uses a :manual:`projection
</tutorial/project-fields-from-query-results>` to limit the fields </tutorial/project-fields-from-query-results>` to limit the fields that are
that are returned. It also limits the results to 5 documents. returned. It also limits the results to 5 documents.
.. code-block:: php .. code-block:: php
<?php <?php
$database = new MongoDB\Client; $collection = (new MongoDB\Client)->example->restaurants;
$collection = $database->selectCollection('example','restaurants');
$restaurants = $collection->find( $cursor = $collection->find(
[ 'cuisine' => 'Italian', 'borough' => 'Manhattan'], [
'cuisine' => 'Italian',
'borough' => 'Manhattan',
],
[ [
'projection' => [ 'projection' => [
'name' => 1, 'borough' => 1, 'cuisine' => 1, 'name' => 1,
'borough' => 1,
'cuisine' => 1,
], ],
'limit' => 4,
] ]
); );
foreach($restaurants as $restaurant) { foreach($cursor as $restaurant) {
var_dump($restaurant); var_dump($restaurant);
}; };
...@@ -279,16 +283,15 @@ The output would then resemble:: ...@@ -279,16 +283,15 @@ The output would then resemble::
string(22) "Angelo Of Mulberry St." string(22) "Angelo Of Mulberry St."
} }
} }
...
Limit, Sort, and Skip Options Limit, Sort, and Skip Options
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In addition to :ref:`projection criteria <php-query-projection>`, In addition to :ref:`projection criteria <php-query-projection>`, you can
you can specify options to limit, sort, and skip documents during queries. specify options to limit, sort, and skip documents during queries.
The following example uses the ``limit`` and ``sort`` options to query The following example uses the ``limit`` and ``sort`` options to query for the
for the five most populous zip codes in the United States: five most populous zip codes in the United States:
.. code-block:: php .. code-block:: php
...@@ -305,7 +308,7 @@ for the five most populous zip codes in the United States: ...@@ -305,7 +308,7 @@ for the five most populous zip codes in the United States:
); );
foreach ($cursor as $document) { foreach ($cursor as $document) {
echo $document['_id'], "\n"; printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']);
} }
The output would then resemble:: The output would then resemble::
...@@ -319,17 +322,16 @@ The output would then resemble:: ...@@ -319,17 +322,16 @@ The output would then resemble::
Complex Queries with Aggregation Complex Queries with Aggregation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MongoDB's :manual:`Aggregation Framework </core/aggregation-pipeline>` MongoDB's :manual:`Aggregation Framework </core/aggregation-pipeline>` allows
allows you to issue complex queries that filter, transform, and group you to issue complex queries that filter, transform, and group collection data.
collection data. The |php-library|\'s The |php-library|\'s :phpmethod:`MongoDB\\Collection::aggregate()` method
:phpmethod:`MongoDB\\Collection::aggregate` method returns a returns a :php:`Traversable <traversable>` object, which you can iterate upon to
:php:`traversable <traversable>` object, which you can iterate upon to
access the results of the aggregation operation. Refer to the access the results of the aggregation operation. Refer to the
:phpmethod:`MongoDB\\Collection::aggregate` method's :ref:`behavior :phpmethod:`MongoDB\\Collection::aggregate()` method's :ref:`behavior
reference <php-agg-method-behavior>` for more about the method's output. reference <php-agg-method-behavior>` for more about the method's output.
The following example lists the 5 US states with the most zip codes The following example lists the 5 US states with the most zip codes associated
associated with them: with them:
.. code-block:: php .. code-block:: php
...@@ -355,7 +357,7 @@ The output would then resemble:: ...@@ -355,7 +357,7 @@ The output would then resemble::
PA has 1458 zip codes PA has 1458 zip codes
IL has 1237 zip codes IL has 1237 zip codes
.. seealso:: :phpmethod:`MongoDB\\Collection::aggregate` reference .. seealso:: :phpmethod:`MongoDB\\Collection::aggregate()`
Update Documents Update Documents
---------------- ----------------
...@@ -363,22 +365,20 @@ Update Documents ...@@ -363,22 +365,20 @@ Update Documents
Update One Document Update One Document
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
Use the :phpmethod:`MongoDB\\Collection::updateOne` method to update a Use the :phpmethod:`MongoDB\\Collection::updateOne()` method to update a single
single document matching a filter. document matching a filter. :phpmethod:`MongoDB\\Collection::updateOne()`
:phpmethod:`MongoDB\\Collection::updateOne` returns a returns a :phpclass:`MongoDB\\UpdateResult` object, which you can use to access
``MongoDB\UpdateResult`` object, which you can use to access statistics statistics about the update operation.
about the update operation.
Update methods have two required parameters: the query filter that Update methods have two required parameters: the query filter that identifies
identifies the document or documents to update, and an update document the document or documents to update, and an update document that specifies what
that specifies what updates to perform. The :phpmethod:`MongoDB\\Collection::updateOne` updates to perform. The :phpmethod:`MongoDB\\Collection::updateOne()` reference
reference describes each parameter in detail. describes each parameter in detail.
The following example inserts two documents into an empty ``users`` collection The following example inserts two documents into an empty ``users`` collection
in the ``demo`` database using the :phpmethod:`MongoDB\\Collection::insertOne` in the ``demo`` database using the :phpmethod:`MongoDB\\Collection::insertOne()`
method, and then updates the documents where the value for the ``state`` method, and then updates the documents where the value for the ``state`` field
field is ``"ny"`` to include is ``"ny"`` to include a ``country`` field set to ``"us"``:
a ``country`` field set to ``"us"``:
.. code-block:: php .. code-block:: php
...@@ -398,16 +398,15 @@ a ``country`` field set to ``"us"``: ...@@ -398,16 +398,15 @@ a ``country`` field set to ``"us"``:
printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
Since the update operation uses the Since the update operation uses the
:phpmethod:`MongoDB\\Collection::updateOne` method, which updates the :phpmethod:`MongoDB\\Collection::updateOne()` method, which updates the first
first document to match the filter criteria, the results would then document to match the filter criteria, the results would then resemble::
resemble::
Matched 1 document(s) Matched 1 document(s)
Modified 1 document(s) Modified 1 document(s)
It is possible for a document to match the filter but *not be modified* It is possible for a document to match the filter but *not be modified* by an
by an update, as is the case where the update sets a field's value to its update, as is the case where the update sets a field's value to its existing
existing value, as in this example: value, as in this example:
.. code-block:: php .. code-block:: php
...@@ -425,34 +424,33 @@ existing value, as in this example: ...@@ -425,34 +424,33 @@ existing value, as in this example:
printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
The number of matched documents and the number of *modified* documents The number of matched documents and the number of *modified* documents would
would therefore not be equal, and the output from the operation would therefore not be equal, and the output from the operation would resemble::
resemble::
Matched 1 document(s) Matched 1 document(s)
Modified 0 document(s) Modified 0 document(s)
.. seealso:: .. seealso::
- :phpmethod:`MongoDB\\Collection::updateOne` reference - :phpmethod:`MongoDB\\Collection::updateOne()`
- :phpmethod:`MongoDB\\Collection::findOneAndUpdate` reference - :phpmethod:`MongoDB\\Collection::findOneAndUpdate()`
Update Many Documents Update Many Documents
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::updateMany` updates one or more documents :phpmethod:`MongoDB\\Collection::updateMany()` updates one or more documents
matching the filter criteria and returns a ``MongoDB\UpdateResult`` object matching the filter criteria and returns a :phpclass:`MongoDB\\UpdateResult`
that you can iterate to access statistics about the update operation. object, which you can use to access statistics about the update operation.
Update methods have two required parameters: the query filter that Update methods have two required parameters: the query filter that identifies
identifies the document or documents to update, and an update document the document or documents to update, and an update document that specifies what
that specifies what updates to perform. The :phpmethod:`MongoDB\\Collection::updateMany` updates to perform. The :phpmethod:`MongoDB\\Collection::updateMany()` reference
reference describes each parameter in detail. describes each parameter in detail.
The following example inserts three documents into an empty ``users`` The following example inserts three documents into an empty ``users`` collection
collection in the ``demo`` database and then uses the :query:`$set` in the ``demo`` database and then uses the :query:`$set` operator to update the
operator to update the documents matching the filter criteria to documents matching the filter criteria to include the ``country`` field with
include the ``country`` field with value ``"us"``: value ``"us"``:
.. code-block:: php .. code-block:: php
...@@ -472,48 +470,46 @@ include the ``country`` field with value ``"us"``: ...@@ -472,48 +470,46 @@ include the ``country`` field with value ``"us"``:
printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
If an update operation results in no change to a document, such as If an update operation results in no change to a document, such as setting the
setting the value of the field to its current value, the number of value of the field to its current value, the number of modified documents can be
modified documents can be less than the number of *matched* documents. less than the number of *matched* documents. Since the update document with
Since the update document with ``name`` of ``"Bob"`` results in no changes ``name`` of ``"Bob"`` results in no changes to the document, the output of the
to the document, the output of the operation therefore resembles:: operation therefore resembles::
Matched 3 document(s) Matched 3 document(s)
Modified 2 document(s) Modified 2 document(s)
.. seealso:: :phpmethod:`MongoDB\\Collection::updateMany` reference .. seealso:: :phpmethod:`MongoDB\\Collection::updateMany()`
Replace Documents Replace Documents
~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
Replacement operations are similar to update operations, but instead Replacement operations are similar to update operations, but instead of updating
of updating a document to include new fields or new field values, a a document to include new fields or new field values, a replacement operation
replacement operation replaces the entire document with a new document, replaces the entire document with a new document, but retains the original
but retains the original document's ``_id`` value. document's ``_id`` value.
The :phpmethod:`MongoDB\\Collection::replaceOne` method replaces a single The :phpmethod:`MongoDB\\Collection::replaceOne()` method replaces a single
document that matches the filter criteria and returns document that matches the filter criteria and returns an instance of
an instance of ``MongoDB\UpdateResult`` that :phpclass:`MongoDB\\UpdateResult`, which you can use to access statistics about
you can use to access statistics about the replacement operation. the replacement operation.
:phpmethod:`MongoDB\\Collection::replaceOne` has two required :phpmethod:`MongoDB\\Collection::replaceOne()` has two required parameters: the
parameters: the query filter that identifies the document or documents query filter that identifies the document or documents to replace, and a
to update, and a replacement document that will replace the original replacement document that will replace the original document in MongoDB. The
document in MongoDB. The :phpmethod:`MongoDB\\Collection::replaceOne` :phpmethod:`MongoDB\\Collection::replaceOne()` reference describes each
reference describes each parameter in detail. parameter in detail.
.. important:: .. important::
Replacement operations replace all of the fields in a document Replacement operations replace all of the fields in a document except the
except the ``_id`` value. To avoid accidentally overwriting or ``_id`` value. To avoid accidentally overwriting or deleting desired fields,
deleting desired fields, use the use the :phpmethod:`MongoDB\\Collection::updateOne()` or
:phpmethod:`MongoDB\\Collection::updateOne` or :phpmethod:`MongoDB\\Collection::updateMany()` methods to update individual
:phpmethod:`MongoDB\\Collection::updateMany` methods to update fields in a document rather than replacing the entire document.
individual fields in a document rather than replacing the entire
document.
The following example inserts one document into an empty ``users`` collection The following example inserts one document into an empty ``users`` collection in
in the ``demo`` database, and then replaces that document with a new one: the ``demo`` database, and then replaces that document with a new one:
.. code-block:: php .. code-block:: php
...@@ -538,26 +534,24 @@ The output would then resemble:: ...@@ -538,26 +534,24 @@ The output would then resemble::
.. seealso:: .. seealso::
- :phpmethod:`MongoDB\\Collection::replaceOne` reference - :phpmethod:`MongoDB\\Collection::replaceOne()`
- :phpmethod:`MongoDB\\Collection::findOneAndReplace` reference - :phpmethod:`MongoDB\\Collection::findOneAndReplace()`
Upsert Upsert
~~~~~~ ~~~~~~
Update and replace operations support an :manual:`upsert Update and replace operations support an :manual:`upsert
</tutorial/update-documents/#upsert-option>` option. When ``upsert`` is </tutorial/update-documents/#upsert-option>` option. When ``upsert`` is ``true``
``true`` *and* no documents match the specified filter, then the *and* no documents match the specified filter, the operation creates a new
operation creates a new document and inserts it. If there *are* matching document and inserts it. If there *are* matching documents, then the operation
documents, then the operation modifies or replaces the matching modifies or replaces the matching document or documents.
document or documents.
When a document is upserted, the ID is accessible via When a document is upserted, the ID is accessible via
``MongoDB\UpdateResult::getUpsertedId()``. :phpmethod:`MongoDB\\UpdateResult::getUpsertedId()`.
The following example uses :phpmethod:`MongoDB\\Collection::updateOne` The following example uses :phpmethod:`MongoDB\\Collection::updateOne()` with
with the ``upsert`` option set to ``true`` into an empty ``users`` the ``upsert`` option set to ``true`` and an empty ``users`` collection in the
collection in the ``demo`` database, therefore inserting the document ``demo`` database, therefore inserting the document into the database:
into the database:
.. code-block:: php .. code-block:: php
...@@ -574,12 +568,19 @@ into the database: ...@@ -574,12 +568,19 @@ into the database:
printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
var_dump($collection->findOne(['_id' => $updateResult->getUpsertedId()])); printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount());
$upsertedDocument = $collection->findOne([
'_id' => $updateResult->getUpsertedId(),
]);
var_dump($upsertedDocument);
The output would then resemble:: The output would then resemble::
Matched 0 document(s) Matched 0 document(s)
Modified 0 document(s) Modified 0 document(s)
Upserted 1 document(s)
object(MongoDB\Model\BSONDocument)#16 (1) { object(MongoDB\Model\BSONDocument)#16 (1) {
["storage":"ArrayObject":private]=> ["storage":"ArrayObject":private]=>
array(3) { array(3) {
...@@ -601,21 +602,22 @@ Delete Documents ...@@ -601,21 +602,22 @@ Delete Documents
Delete One Document Delete One Document
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::deleteOne()` method deletes a single
The :phpmethod:`MongoDB\\Collection::deleteOne` method deletes a single
document that matches the filter criteria and returns a document that matches the filter criteria and returns a
``MongoDB\DeleteResult`` object that you can use to access statistics :phpclass:`MongoDB\\DeleteResult`, which you can use to access statistics about
about the delete operation. If multiple documents match the filter the delete operation.
criteria, :phpmethod:`MongoDB\\Collection::deleteOne` deletes the
:term:`first <natural order>` matching document.
:phpmethod:`MongoDB\\Collection::deleteOne` has one required parameter: If multiple documents match the filter criteria,
a query filter that specifies the document to delete. Refer to the :phpmethod:`MongoDB\\Collection::deleteOne()` deletes the :term:`first
:phpmethod:`MongoDB\\Collection::deleteOne` reference for full method documentation. <natural order>` matching document.
:phpmethod:`MongoDB\\Collection::deleteOne()` has one required parameter: a
query filter that specifies the document to delete. Refer to the
:phpmethod:`MongoDB\\Collection::deleteOne()` reference for full method
documentation.
The following operation deletes the first document where the ``state`` The following operation deletes the first document where the ``state`` field's
value is ``ny``: value is ``"ny"``:
.. code-block:: php .. code-block:: php
...@@ -634,24 +636,22 @@ The output would then resemble:: ...@@ -634,24 +636,22 @@ The output would then resemble::
Deleted 1 document(s) Deleted 1 document(s)
.. seealso:: :phpmethod:`MongoDB\\Collection::deleteOne` reference. .. seealso:: :phpmethod:`MongoDB\\Collection::deleteOne()`
Delete Many Documents Delete Many Documents
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::deleteMany` deletes all of the :phpmethod:`MongoDB\\Collection::deleteMany()` deletes all of the documents that
documents that match the filter criteria and returns a match the filter criteria and returns a :phpclass:`MongoDB\\DeleteResult`, which
``MongodB\DeleteResult`` object that you can use to access statistics you can use to access statistics about the delete operation.
about the delete op eration.
:phpmethod:`MongoDB\\Collection::deleteMany` has one required
parameter: a query filter that specifies the document to delete. Refer
to the :phpmethod:`MongoDB\\Collection::deleteMany` reference for full
method documentation.
:phpmethod:`MongoDB\\Collection::deleteMany()` has one required parameter: a
query filter that specifies the document to delete. Refer to the
:phpmethod:`MongoDB\\Collection::deleteMany()` reference for full method
documentation.
The following operation deletes all of the documents where the The following operation deletes all of the documents where the ``state`` field's
``state`` field has value ``"ny"``: value is ``"ny"``:
.. code-block:: php .. code-block:: php
...@@ -670,4 +670,4 @@ The output would then resemble:: ...@@ -670,4 +670,4 @@ The output would then resemble::
Deleted 2 document(s) Deleted 2 document(s)
.. seealso:: :phpmethod:`MongoDB\\Collection::deleteMany` reference .. seealso:: :phpmethod:`MongoDB\\Collection::deleteMany()`
...@@ -4,12 +4,11 @@ Indexes ...@@ -4,12 +4,11 @@ Indexes
.. default-domain:: mongodb .. default-domain:: mongodb
Indexes support the efficient execution of queries in MongoDB. Without Indexes support the efficient execution of queries in MongoDB. Without indexes,
indexes, MongoDB must perform a *collection scan*, i.e. scan every MongoDB must perform a *collection scan*, i.e. scan every document in a
document in a collection, to select those documents that match the collection, to select those documents that match the query statement. If an
query statement. If an appropriate index exists for a query, appropriate index exists for a query, MongoDB can use the index to limit the
MongoDB can use the index to limit the number of documents it must number of documents it must inspect.
inspect.
The PHP driver supports managing indexes through the The PHP driver supports managing indexes through the
:phpclass:`MongoDB\\Collection` class, which implements MongoDB's :phpclass:`MongoDB\\Collection` class, which implements MongoDB's
...@@ -19,20 +18,20 @@ and `Enumerating Indexes ...@@ -19,20 +18,20 @@ and `Enumerating Indexes
<https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst>`_ <https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst>`_
specifications. specifications.
This document provides an introduction to creating, listing, and This document provides an introduction to creating, listing, and dropping
dropping indexes using the |php-library|. The MongoDB Manual's indexes using the |php-library|. The MongoDB Manual's :manual:`Indexes
:manual:`Indexes Section </indexes>` provides more thorough </indexes>` reference provides more thorough information about indexing in
information about indexing in MongoDB. MongoDB.
Create Indexes Create Indexes
-------------- --------------
Create indexes with the :phpmethod:`MongoDB\\Collection::createIndex` Create indexes with the :phpmethod:`MongoDB\\Collection::createIndex()` or
and :phpmethod:`MongoDB\\Collection::createIndexes` methods. Refer to :phpmethod:`MongoDB\\Collection::createIndexes()` methods. Refer to the method
the method reference for more details about each method. reference for more details about each method.
The following example creates an ascending index on the ``state`` field The following example creates an ascending index on the ``state`` field using
using the :phpmethod:`createIndex` method: the :phpmethod:`createIndex() <MongoDB\\Collection::createIndex>` method:
.. code-block:: php .. code-block:: php
...@@ -44,24 +43,23 @@ using the :phpmethod:`createIndex` method: ...@@ -44,24 +43,23 @@ using the :phpmethod:`createIndex` method:
var_dump($result); var_dump($result);
When you create an index, the method returns its name, which is When you create an index, the method returns its name, which is automatically
automatically generated from its specification. The above example would generated from its specification. The above example would output something
output something similar to:: similar to::
string(7) "state_1" string(7) "state_1"
List Indexes List Indexes
------------ ------------
The :phpmethod:`MongoDB\\Collection::listIndexes` method provides The :phpmethod:`MongoDB\\Collection::listIndexes()` method provides information
information about the indexes in a collection. about the indexes in a collection. The
:phpmethod:`MongoDB\\Collection::listIndexes` method returns an :phpmethod:`MongoDB\\Collection::listIndexes()` method returns an iterator of
iterator of ``MongoDB\Model\IndexInfo`` objects, which you can use to :phpclass:`MongoDB\\Model\\IndexInfo` objects, which you can use to view
view information about each index. Refer to the method reference for information about each index. Refer to the method reference for more details.
more details about each method.
The following example lists all indexes in the ``zips`` collection in The following example lists all indexes in the ``zips`` collection in the
the ``demo`` database: ``demo`` database:
.. code-block:: php .. code-block:: php
...@@ -105,9 +103,10 @@ The output would resemble:: ...@@ -105,9 +103,10 @@ The output would resemble::
Drop Indexes Drop Indexes
------------ ------------
The :phpmethod:`MongoDB\\Collection::dropIndex` lets you drop a single index while The :phpmethod:`MongoDB\\Collection::dropIndex()` method lets you drop a single
:phpmethod:`MongoDB\\Collection::dropIndexes` drops all of the indexes on a collection. index while :phpmethod:`MongoDB\\Collection::dropIndexes()` drops all of the
Refer to the method reference for more details about each method. indexes on a collection. Refer to the method reference for more details about
each method.
The following example drops a single index by its name, ``state_1``: The following example drops a single index by its name, ``state_1``:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment