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