Commit 0d3496dd authored by Jeremy Mikola's avatar Jeremy Mikola

Merge pull request #495

parents f83e11d9 5f5442cb
......@@ -13,5 +13,6 @@ Reference
/reference/class/MongoDBCollection
/reference/class/MongoDBGridFSBucket
/reference/write-result-classes
/reference/result-classes
/reference/enumeration-classes
/reference/exception-classes
================================
MongoDB\\ChangeStream::current()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::current()
Returns the current event in the change stream.
.. code-block:: php
function current(): array|object|null
The structure of each event document will vary based on the operation type.
See :manual:`Change Events </reference/change-events/>` in the MongoDB manual
for more information.
Return Values
-------------
An array or object for the current event in the change stream, or ``null`` if
there is no current event (i.e. :phpmethod:`MongoDB\\ChangeStream::valid()`
returns ``false``). The return type will depend on the ``typeMap`` option for
:phpmethod:`MongoDB\\Collection::watch()`.
Examples
--------
This example reports events while iterating a change stream.
.. code-block:: php
<?php
$uri = 'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet';
$collection = (new MongoDB\Client($uri))->test->inventory;
$changeStream = $collection->watch();
for ($changeStream->rewind(); true; $changeStream->next()) {
if ( ! $changeStream->valid()) {
continue;
}
$event = $changeStream->current();
$ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']);
$id = json_encode($event['documentKey']['_id']);
switch ($event['operationType']) {
case 'delete':
printf("Deleted document in %s with _id: %s\n\n", $ns, $id);
break;
case 'insert':
printf("Inserted new document in %s\n", $ns);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'replace':
printf("Replaced new document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'update':
printf("Updated document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['updateDescription']), "\n\n";
break;
}
}
Assuming that a document was inserted, updated, and deleted while the above
script was iterating the change stream, the output would then resemble:
.. code-block:: none
Inserted new document in test.inventory
{"_id":{"$oid":"5a81fc0d6118fd1af1790d32"},"name":"Widget","quantity":5}
Updated document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
{"updatedFields":{"quantity":4},"removedFields":[]}
Deleted document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
See Also
--------
- :phpmethod:`MongoDB\\Collection::watch()`
- :php:`Iterator::current() <iterator.current>`
- :ref:`Tailable Cursor Iteration <php-tailable-cursor>`
- :manual:`Change Streams </changeStreams>` documentation in the MongoDB manual
- :manual:`Change Events </reference/change-events/>` documentation in the
MongoDB manual
\ No newline at end of file
====================================
MongoDB\\ChangeStream::getCursorId()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::getCursorId()
Returns the change stream cursor's ID.
.. code-block:: php
function getCursorId(): MongoDB\Driver\CursorId
Return Values
-------------
A :php:`MongoDB\\Driver\\CursorId <class.mongodb-driver-cursorid>` object.
Examples
--------
This example reports the cursor ID for a change stream.
.. code-block:: php
<?php
$uri = 'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet';
$collection = (new MongoDB\Client($uri))->test->inventory;
$changeStream = $collection->watch();
var_dump($changeStream->getCursorId());
The output would then resemble::
object(MongoDB\Driver\CursorId)#5 (1) {
["id"]=>
int(8462642181784669708)
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::watch()`
- :php:`MongoDB\\Driver\\CursorId <class.mongodb-driver-cursorid>`
- :php:`MongoDB\\Driver\\Cursor::getId() <manual/en/mongodb-driver-cursor.getid.php>`
============================
MongoDB\\ChangeStream::key()
============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::key()
Returns the index of the current event in the change stream.
.. code-block:: php
function key(): integer|null
The index of the first event in a change stream starts at zero and will
increment by one for each subsequent event.
Return Values
-------------
The index of the current event in the change stream, or ``null`` if there is no
current event (i.e. :phpmethod:`MongoDB\\ChangeStream::valid()` returns
``false``).
Examples
--------
This example reports the index of events while iterating a change stream.
.. code-block:: php
<?php
$uri = 'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet';
$collection = (new MongoDB\Client($uri))->test->inventory;
$changeStream = $collection->watch();
for ($changeStream->rewind(); true; $changeStream->next()) {
if ( ! $changeStream->valid()) {
continue;
}
$event = $changeStream->current();
printf("%d: %s\n", $changeStream->key(), $event['operationType']);
}
Assuming that a document was inserted, updated, and deleted while the above
script was iterating the change stream, the output would then resemble:
.. code-block:: none
0: insert
1: update
2: delete
See Also
--------
- :phpmethod:`MongoDB\\Collection::watch()`
- :php:`Iterator::key() <iterator.key>`
- :ref:`Tailable Cursor Iteration <php-tailable-cursor>`
- :manual:`Change Streams </changeStreams>` documentation in the MongoDB manual
\ No newline at end of file
=============================
MongoDB\\ChangeStream::next()
=============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::next()
Advances the change stream and attempts to load the next event.
.. code-block:: php
function next(): void
.. note::
Advancing the change stream does not guarantee that there will be a
current event to access. You should still call
:phpmethod:`MongoDB\\ChangeStream::valid()` to check for a current event
at each step of iteration.
Errors/Exceptions
-----------------
.. include:: /includes/extracts/error-driver-runtimeexception.rst
See Also
--------
- :phpmethod:`MongoDB\\Collection::watch()`
- :php:`Iterator::next() <iterator.next>`
- :ref:`Tailable Cursor Iteration <php-tailable-cursor>`
- :manual:`Change Streams </changeStreams>` documentation in the MongoDB manual
===============================
MongoDB\\ChangeStream::rewind()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::rewind()
Rewinds the change stream and attempts to load the first event.
.. code-block:: php
function rewind(): void
This method should be called at the start of change stream iteration.
.. note::
Rewinding the change stream does not guarantee that there will be a
current event to access. You should still call
:phpmethod:`MongoDB\\ChangeStream::valid()` to check for a current event
at each step of iteration. After initially rewinding the change stream,
:phpmethod:`MongoDB\\ChangeStream::next()` should be used to iterate
further.
Errors/Exceptions
-----------------
:php:`MongoDB\\Driver\\Exception\\LogicException
<mongodb-driver-exception-logicexception>` if this method is called after a call
to :phpmethod:`MongoDB\\ChangeStream::next()` (i.e. the underlying
:php:`MongoDB\\Driver\\Cursor <class.mongodb-driver-cursor>` has already been
advanced).
.. include:: /includes/extracts/error-driver-runtimeexception.rst
See Also
--------
- :phpmethod:`MongoDB\\Collection::watch()`
- :php:`Iterator::rewind() <iterator.rewind>`
- :ref:`Tailable Cursor Iteration <php-tailable-cursor>`
- :manual:`Change Streams </changeStreams>` documentation in the MongoDB manual
==============================
MongoDB\\ChangeStream::valid()
==============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\ChangeStream::valid()
Returns whether there is a current event in the change stream.
.. code-block:: php
function valid(): boolean
When manually iterating the change stream using
:php:`Iterator </manual/en/class.iterator.php>` methods, this method should
be used to determine if :phpmethod:`MongoDB\\ChangeStream::current()` and
:phpmethod:`MongoDB\\ChangeStream::key()` can be called.
Return Values
-------------
A boolean indicating whether there is a current event in the change stream.
See Also
--------
- :phpmethod:`MongoDB\\Collection::watch()`
- :php:`Iterator::valid() <iterator.valid>`
- :ref:`Tailable Cursor Iteration <php-tailable-cursor>`
- :manual:`Change Streams </changeStreams>` documentation in the MongoDB manual
......@@ -36,7 +36,7 @@ Return Values
-------------
A :phpclass:`MongoDB\\MapReduceResult` object, which allows for iteration of
mapReduce results irrespective of the output method (e.g. inline, collection)
map-reduce results irrespective of the output method (e.g. inline, collection)
via the :php:`IteratorAggregate <iteratoraggregate>` interface. It also
provides access to command statistics.
......@@ -117,7 +117,6 @@ The output would then resemble::
float(3665228)
}
See Also
--------
......
......@@ -46,9 +46,71 @@ Errors/Exceptions
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst
Examples
--------
This example reports events while iterating a change stream.
.. code-block:: php
<?php
$uri = 'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet';
$collection = (new MongoDB\Client($uri))->test->inventory;
$changeStream = $collection->watch();
for ($changeStream->rewind(); true; $changeStream->next()) {
if ( ! $changeStream->valid()) {
continue;
}
$event = $changeStream->current();
$ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']);
$id = json_encode($event['documentKey']['_id']);
switch ($event['operationType']) {
case 'delete':
printf("Deleted document in %s with _id: %s\n\n", $ns, $id);
break;
case 'insert':
printf("Inserted new document in %s\n", $ns);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'replace':
printf("Replaced new document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['fullDocument']), "\n\n";
break;
case 'update':
printf("Updated document in %s with _id: %s\n", $ns, $id);
echo json_encode($event['updateDescription']), "\n\n";
break;
}
}
Assuming that a document was inserted, updated, and deleted while the above
script was iterating the change stream, the output would then resemble:
.. code-block:: none
Inserted new document in test.inventory
{"_id":{"$oid":"5a81fc0d6118fd1af1790d32"},"name":"Widget","quantity":5}
Updated document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
{"updatedFields":{"quantity":4},"removedFields":[]}
Deleted document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
See Also
--------
- :manual:`Aggregation Pipeline </core/aggregation-pipeline>` documentation in
the MongoDB Manual
- :manual:`Change Streams </changeStreams>` documentation in the MongoDB manual
- :manual:`Change Events </reference/change-events/>` documentation in the
MongoDB manual
=====================================
MongoDB\\MapReduceResult::getCounts()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\MapReduceResult::getCounts()
Returns count statistics for the map-reduce operation.
.. code-block:: php
function getCounts(): array
Return Values
-------------
An array of count statistics for the map-reduce operation.
Examples
--------
This example reports the count statistics for a map-reduce operation.
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->test->zips;
$map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }');
$reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }');
$out = ['inline' => 1];
$result = $collection->mapReduce($map, $reduce, $out);
var_dump($result->getCounts());
The output would then resemble::
array(4) {
["input"]=>
int(29353)
["emit"]=>
int(29353)
["reduce"]=>
int(180)
["output"]=>
int(51)
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::mapReduce()`
- :manual:`mapReduce </reference/command/mapReduce>` command reference in the
MongoDB manual
==============================================
MongoDB\\MapReduceResult::getExecutionTimeMS()
==============================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\MapReduceResult::getExecutionTimeMS()
Returns the execution time in milliseconds of the map-reduce operation.
.. code-block:: php
function getExecutionTimeMS(): integer
Return Values
-------------
An integer denoting the execution time in milliseconds for the map-reduce
operation.
Examples
--------
This example reports the execution time for a map-reduce operation.
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->test->zips;
$map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }');
$reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }');
$out = ['inline' => 1];
$result = $collection->mapReduce($map, $reduce, $out);
var_dump($result->getExecutionTimeMS());
The output would then resemble::
int(244)
See Also
--------
- :phpmethod:`MongoDB\\Collection::mapReduce()`
- :manual:`mapReduce </reference/command/mapReduce>` command reference in the
MongoDB manual
=======================================
MongoDB\\MapReduceResult::getIterator()
=======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\MapReduceResult::getIterator()
Returns a php:`Traversable <traversable>`, which may be used to iterate
through the results of the map-reduce operation.
.. code-block:: php
function getIterator(): Traversable
Return Values
-------------
A :php:`Traversable <traversable>`, which may be used to iterate through the
results of the map-reduce operation.
Example
-------
This example iterates through the results of a map-reduce operation.
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->test->zips;
$map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }');
$reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }');
$out = ['inline' => 1];
$result = $collection->mapReduce($map, $reduce, $out);
foreach ($result as $population) {
var_dump($population);
};
The output would then resemble::
object(stdClass)#2293 (2) {
["_id"]=>
string(2) "AK"
["value"]=>
float(544698)
}
object(stdClass)#2300 (2) {
["_id"]=>
string(2) "AL"
["value"]=>
float(4040587)
}
object(stdClass)#2293 (2) {
["_id"]=>
string(2) "AR"
["value"]=>
float(2350725)
}
object(stdClass)#2300 (2) {
["_id"]=>
string(2) "AZ"
["value"]=>
float(3665228)
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::mapReduce()`
- :php:`IteratorAggregate::getIterator() <manual/en/iteratoraggregate.getiterator.php>`
=====================================
MongoDB\\MapReduceResult::getTiming()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\MapReduceResult::getTiming()
Returns timing statistics for the map-reduce operation.
.. code-block:: php
function getTiming(): array
Timing statistics will only be available if the ``verbose`` option was
specified for :phpmethod:`MongoDB\\Collection::mapReduce()`.
Return Values
-------------
An array of timing statistics for the map-reduce operation. If no timing
statistics are available, the array will be empty.
Examples
--------
This example specifies the ``verbose`` option for
:phpmethod:`MongoDB\\Collection::mapReduce()` and reports the timing statistics
for a map-reduce operation.
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->test->zips;
$map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }');
$reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }');
$out = ['inline' => 1];
$result = $collection->mapReduce($map, $reduce, $out, ['verbose' => true]);
var_dump($result->getTiming());
The output would then resemble::
array(5) {
["mapTime"]=>
int(163)
["emitLoop"]=>
int(233)
["reduceTime"]=>
int(9)
["mode"]=>
string(5) "mixed"
["total"]=>
int(233)
}
See Also
--------
- :phpmethod:`MongoDB\\Collection::mapReduce()`
- :manual:`mapReduce </reference/command/mapReduce>` command reference in the
MongoDB manual
==============
Result Classes
==============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
MongoDB\\ChangeStream
---------------------
.. versionadded:: 1.3
Definition
~~~~~~~~~~
.. phpclass:: MongoDB\\ChangeStream
This class extends PHP's :php:`Iterator <manual/en/class.iterator.php>`
interface. An instance of this class is returned by
:phpmethod:`MongoDB\\Collection::watch()`.
This class allows for iteration of events in a change stream. It also allows
iteration to automatically resume after certain errors, such as a replica set
failover.
Methods
~~~~~~~
.. toctree::
:titlesonly:
/reference/method/MongoDBChangeStream-current
/reference/method/MongoDBChangeStream-getCursorId
/reference/method/MongoDBChangeStream-key
/reference/method/MongoDBChangeStream-next
/reference/method/MongoDBChangeStream-rewind
/reference/method/MongoDBChangeStream-valid
----
MongoDB\\MapReduceResult
------------------------
.. versionadded:: 1.2
Definition
~~~~~~~~~~
.. phpclass:: MongoDB\\MapReduceResult
This class extends PHP's :php:`IteratorAggregate <iteratoraggregate>`
interface. An instance of this class is returned by
:phpmethod:`MongoDB\\Collection::mapReduce()`.
This class allows for iteration of map-reduce results irrespective of the
output method (e.g. inline, collection). It also provides access to command
statistics.
Methods
~~~~~~~
.. toctree::
:titlesonly:
/reference/method/MongoDBMapReduceResult-getCounts
/reference/method/MongoDBMapReduceResult-getExecutionTimeMS
/reference/method/MongoDBMapReduceResult-getIterator
/reference/method/MongoDBMapReduceResult-getTiming
......@@ -11,5 +11,5 @@ Tutorials
/tutorial/decimal128
/tutorial/gridfs
/tutorial/indexes
/tutorial/example-data
/tutorial/tailable-cursor
/tutorial/example-data
===============
Tailable Cursor
===============
.. _php-tailable-cursor:
=========================
Tailable Cursor Iteration
=========================
.. default-domain:: mongodb
......
......@@ -27,10 +27,10 @@ use IteratorIterator;
use Iterator;
/**
* Iterator for the changeStream command.
* Iterator for a change stream.
*
* @api
* @see \MongoDB\Collection::changeStream()
* @see \MongoDB\Collection::watch()
* @see http://docs.mongodb.org/manual/reference/command/changeStream/
*/
class ChangeStream implements Iterator
......@@ -43,6 +43,9 @@ class ChangeStream implements Iterator
const CURSOR_NOT_FOUND = 43;
/**
* Constructor.
*
* @internal
* @param Cursor $cursor
* @param callable $resumeCallable
*/
......
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