Commit 749f0aa0 authored by Jeremy Mikola's avatar Jeremy Mikola

Merge pull request #144

parents c31e5300 6ece2bcf
# MongoDB\Client # MongoDB\Client
`MongoDB\Client` serves as an entry point for the library and driver. It is The MongoDB\Client class serves as an entry point for the library. It is the
constructed with the same arguments as the driver's `MongoDB\Driver\Manager` preferred class for connecting to a MongoDB server or cluster of servers and
class, which it composes. Additional reference may be found in the serves as a gateway for accessing individual databases and collections. It is
[`MongoDB\Driver\Manager::__construct`](http://php.net/manual/en/mongodb-driver-manager.construct.php]) analogous to the driver's [MongoDB\Driver\Manager][manager] class, which it
and composes.
[Connection String](https://docs.mongodb.org/manual/reference/connection-string/)
documentation.
[manager]: http://php.net/mongodb-driver-manager
---
## __construct()
```php
function __construct($uri = 'mongodb://localhost:27017', array $uriOptions = [], array $driverOptions = [])
``` ```
/* By default, the driver connects to mongodb://localhost:27017 */
$client = new MongoDB\Client;
/* Any URI options will be merged into the URI string */ Constructs a new Client instance.
Additional URI options may be provided as the second argument and will take
precedence over any like options present in the URI string (e.g. authentication
credentials, query string parameters).
Driver options may be provided as the third argument. In addition to any options
supported by the extension, this library allows you to specify a default
type map to apply to the cursors it creates. A more thorough description of type
maps may be found in the driver's [Persistence documentation][typemap].
[typemap]: http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps
### Supported URI Options
See [MongoDB\Driver\Manager::__construct()][manager-construct] and the
[MongoDB manual][connection-string].
[manager-construct]: http://php.net/manual/en/mongodb-driver-manager.construct.php
[connection-string]: https://docs.mongodb.org/manual/reference/connection-string/
### Supported Driver Options
typeMap (array)
: Default type map for cursors and BSON documents.
### Example
By default, the driver connects to a standalone server on localhost via port
27017. The following example demonstrates how to connect to a replica set.
Additionally, it demonstrates a replica set with a custom read preference:
```
<?php
$client = new MongoDB\Client( $client = new MongoDB\Client(
'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet', 'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet',
['readPreference' => 'secondaryPreferred'] [
'readPreference' => 'secondaryPreferred'
]
); );
``` ```
Driver options may be provided as the third argument. In addition to options By default, the library will unserialize BSON documents and arrays as
supported by the extension, the PHP library allows you to specify a default MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray objects, respectively.
type map to apply to the cursors it creates. A more thorough description of type The following example demonstrates how to have the library unserialize
maps may be found in the driver's everything as a PHP array, as was done in the legacy
[Persistence documentation](http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps). [mongo extension][ext-mongo]:
[ext-mongo]: http://php.net/mongo
``` ```
/* This example instructs the library to unserialize root and embedded BSON <?php
* documents as PHP arrays, like the legacy driver (i.e. ext-mongo). */
$client = new MongoDB\Client(null, [], [ $client = new MongoDB\Client(
'typeMap' => ['root' => 'array', 'document' => 'array'], null,
[],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
); );
``` ```
By default, the library will unserialize BSON documents and arrays as ### See Also
`MongoDB\Model\BSONDocument` and `MongoDB\Model\BSONArray` objects,
respectively. Each of these model classes extends PHP's * [MongoDB\Driver\Manager::__construct()][manager-construct]
[`ArrayObject`](http://php.net/arrayobject) class and implements the driver's * [MongoDB Manual: Connection String][connection-string]
[`MongoDB\BSON\Serializable`](http://php.net/mongodb-bson-serializable) and
[`MongoDB\BSON\Unserializable`](http://php.net/mongodb-bson-unserializable)
interfaces.
## Selecting Databases and Collections ---
The Client class provides methods for creating Database or Collection instances ## __get()
(using its internal Manager instance). When selecting a Database or Collection,
the child will inherit options (e.g. read preference, type map) from the Client.
New options may also be provided to the `selectDatabase()` and
`selectCollection()` methods.
```php
function __get($databaseName): MongoDB\Database
``` ```
Select a database.
The Database will inherit options (e.g. read preference, type map) from the
Client object. Use [selectDatabase()](#selectdatabase) to override any options.
**Note:** databases whose names contain special characters (e.g. "-") may be
selected with complex syntax (e.g. `$client->{"that-database"}`) or
[selectDatabase()](#selectdatabase).
### Example
The following example selects the "demo" and "another-app" databases:
```
<?php
$client = new MongoDB\Client; $client = new MongoDB\Client;
/* Select the "demo" database */ $demo = $client->demo;
$db = $client->selectDatabase('demo'); $anotherApp = $client->{'another-app'};
```
/* Select the "demo.users" collection */ ### See Also
$collection = $client->selectCollection('demo', 'users');
* [MongoDB\Client::selectDatabase()](#selectdatabase)
* [PHP Manual: Property Overloading](http://php.net/oop5.overloading#object.get)
---
/* selectDatabase() and selectCollection() also take an options array, which can ## dropDatabase
* override any options inherited from the Client. */
$db = $client->selectDatabase('demo', [
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]);
/* The property accessor may also be used to select a database without ```php
* specifying additional options. PHP's complex syntax may be used for selecting function dropDatabase($databaseName, array $options = []): array|object
* databases whose names contain special characters (e.g. "-"). */
$db = $client->demo;
$db = $client->{'another-app'};
``` ```
## Database Management Drop a database. Returns the command result document.
The Client class has several methods for managing databases. ### Supported Options
### Dropping Databases typeMap (array)
: Type map for BSON deserialization. This will only be used for the returned
command result document.
### Example
The following example drops the "demo" database:
``` ```
<?php
$client = new MongoDB\Client; $client = new MongoDB\Client;
$result = $client->dropDatabase('demo'); $result = $client->dropDatabase('demo');
var_dump($result); var_dump($result);
``` ```
...@@ -98,12 +161,36 @@ object(MongoDB\Model\BSONDocument)#8 (1) { ...@@ -98,12 +161,36 @@ object(MongoDB\Model\BSONDocument)#8 (1) {
} }
``` ```
### Enumerating Databases ### See Also
* [MongoDB\Database::drop()](database.md#drop)
* [MongoDB Manual: dropDatabase command](http://docs.mongodb.org/manual/reference/command/dropDatabase/)
---
## listDatabases()
```php
function listDatabases(array $options = []): MongoDB\Model\DatabaseInfoIterator
``` ```
Returns information for all database on the server. Elements in the returned
iterator will be MongoDB\Model\DatabaseInfo objects.
### Supported Options
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
### Example
The following example lists all databases on the server:
```
<?php
$client = new MongoDB\Client; $client = new MongoDB\Client;
/* listDatabases() returns an iterator of MongoDB\Model\DatabaseInfo objects */
foreach ($client->listDatabases() as $databaseInfo) { foreach ($client->listDatabases() as $databaseInfo) {
var_dump($databaseInfo); var_dump($databaseInfo);
} }
...@@ -129,3 +216,139 @@ object(MongoDB\Model\DatabaseInfo)#7 (3) { ...@@ -129,3 +216,139 @@ object(MongoDB\Model\DatabaseInfo)#7 (3) {
bool(false) bool(false)
} }
``` ```
### See Also
* [MongoDB Manual: listDatabases command](http://docs.mongodb.org/manual/reference/command/listDatabases/)
---
## selectCollection()
```php
function selectCollection($databaseName, $collectionName, array $options = []): MongoDB\Collection
```
Select a collection on the server.
The Collection will inherit options (e.g. read preference, type map) from the
Client object unless otherwise specified.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for collection operations. Defaults to the
Client's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for collection operations. Defaults to
the Client's read preference.
typeMap (array)
: Default type map for cursors and BSON documents. Defaults to the Client's
type map.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for collection operations. Defaults to the
Client's write concern.
### Example
The following example selects the "demo.users" collection:
```
<?php
$client = new MongoDB\Client;
$collection = $client->selectCollection('demo', 'users');
```
The following examples selects the "demo.users" collection with a custom read
preference:
```
<?php
$client = new MongoDB\Client;
$collection = $client->selectCollection(
'demo',
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
```
### See Also
* [MongoDB\Collection::__construct()](collection.md#__construct)
* [MongoDB\Client::__get()](#__get)
---
## selectDatabase()
```php
function selectDatabase($databaseName array $options = []): MongoDB\Collection
```
Select a database on the server.
The Database will inherit options (e.g. read preference, type map) from the
Client object unless otherwise specified.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for database operations. Defaults to the
Client's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for database operations. Defaults to the
Client's read preference.
typeMap (array)
: Default type map for cursors and BSON documents. Defaults to the Client's
type map.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for database operations. Defaults to the
Client's write concern.
### Example
The following example selects the "demo" database:
```
<?php
$client = new MongoDB\Client;
$db = $client->selectDatabase('demo');
```
The following examples selects the "demo" database with a custom read
preference:
```
<?php
$client = new MongoDB\Client;
$db = $client->selectDatabase(
'demo',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
```
### See Also
* [MongoDB\Database::__construct()](database.md#__construct)
* [MongoDB\Client::__get()](#__get)
---
# MongoDB\Collection # MongoDB\Collection
`MongoDB\Collection` is perhaps the most useful class in this library. It The MongoDB\Collection class provides methods for common operations on a
provides methods for common operations on a collection, such as inserting collection and its documents. This includes, but is not limited to, CRUD
documents, querying, updating, counting, etc. operations (e.g. inserting, querying, counting) and managing indexes.
A Collection may be constructed directly (using the extension's Manager class) A Collection may be constructed directly (using the extension's Manager class),
or selected from the library's Client class. It supports the following options: selected from the library's [Client](client.md) or [Database](database.md)
classes, or cloned from an existing Collection via
[withOptions()](#withoptions). It supports the following options:
* [readConcern](http://php.net/mongodb-driver-readconcern) * [readConcern](http://php.net/mongodb-driver-readconcern)
* [readPreference](http://php.net/mongodb-driver-readpreference) * [readPreference](http://php.net/mongodb-driver-readpreference)
* [typeMap](http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps) * [typeMap](http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps)
* [writeConcern](http://php.net/mongodb-driver-writeconcern) * [writeConcern](http://php.net/mongodb-driver-writeconcern)
If any options are omitted, they will be inherited from the Manager constructor Operations within the Collection class (e.g. [find()](#find),
argument or object from which the Collection was selected. [insertOne()](#insertone)) will generally inherit the Collection's options. One
notable exception to this rule is that [aggregate()](#aggregate) (when not using
a cursor), [distinct()](#distinct), and the [findAndModify][findandmodify]
helpers do not yet support a "typeMap" option due to a driver limitation. This
means that they will always return BSON documents and arrays as stdClass objects
and arrays, respectively.
Operations within the Collection class (e.g. `find()`, `insertOne()`) will [findandmodify]: http://docs.mongodb.org/manual/reference/command/findAndModify/
generally inherit the Collection's options. One notable exception to this rule
is that `aggregate()` (when not using a cursor) and the `findAndModify` variants
do not yet support a type map option due to a driver limitation. This means that
they will return BSON documents and arrays as `stdClass` objects and PHP arrays,
respectively.
## Collection-level Operations ---
The Collection class has methods for collection-level operations, such as ## __construct()
dropping the collection, CRUD operations, or managing the collection's indexes.
### Dropping the Collection ```php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, $collectionName, array $options = [])
```
If the Collection is constructed explicitly, any omitted options will be
inherited from the Manager object. If the Collection is selected from a
[Client](client.md) or [Database](database.md) object, options will be
inherited from that object.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for collection operations. Defaults to the
Manager's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for collection operations. Defaults to
the Manager's read preference.
typeMap (array)
: Default type map for cursors and BSON documents.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for collection operations. Defaults to the
Manager's write concern.
### See Also
* [MongoDB\Collection::withOptions()](#withoptions)
* [MongoDB\Database::selectCollection()](database.md#selectcollection)
---
## aggregate()
```php
function aggregate(array $pipeline, array $options = []): Traversable
```
Executes an aggregation framework pipeline on the collection.
This method's return value depends on the MongoDB server version and the
"useCursor" option. If "useCursor" is true, a MongoDB\Driver\Cursor will be
returned; otherwise, an ArrayIterator is returned, which wraps the "result"
array from the command response document.
**Note:** BSON deserialization of inline aggregation results (i.e. not using a
command cursor) does not yet support a "typeMap" options; however, classes
implementing [MongoDB\BSON\Persistable][persistable] will still be deserialized
according to the [Persistence][persistence] specification.
[persistable]: http://php.net/mongodb-bson-persistable
[persistence]: http://php.net/manual/en/mongodb.persistence.deserialization.php
### Supported Options
allowDiskUse (boolean)
: Enables writing to temporary files. When set to true, aggregation stages can
write data to the _tmp sub-directory in the dbPath directory. The default is
false.
batchSize (integer)
: The number of documents to return per batch.
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation. This only
applies when the $out stage is specified.
<br><br>
For servers < 3.2, this option is ignored as document level validation is
not available.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
readConcern (MongoDB\Driver\ReadConcern)
: Read concern. Note that a "majority" read concern is not compatible with the
$out stage.
<br><br>
For servers < 3.2, this option is ignored as read concern is not available.
readPreference (MongoDB\Driver\ReadPreference)
: Read preference.
typeMap (array)
: Type map for BSON deserialization. This will be applied to the returned
Cursor (it is not sent to the server).
<br><br>
This is currently not supported for inline aggregation results (i.e.
useCursor option is false or the server versions < 2.6).
useCursor (boolean)
: Indicates whether the command will request that the server provide results
using a cursor. The default is true.
<br><br>
For servers < 2.6, this option is ignored as aggregation cursors are not
available.
<br><br>
For servers >= 2.6, this option allows users to turn off cursors if
necessary to aid in mongod/mongos upgrades.
### See Also
* [MongoDB Manual: aggregate command](http://docs.mongodb.org/manual/reference/command/aggregate/)
* [MongoDB Manual: Aggregation Pipeline](https://docs.mongodb.org/manual/core/aggregation-pipeline/)
---
## bulkWrite()
```php
function bulkWrite(array $operations, array $options = []): MongoDB\BulkWriteResult
```
Executes multiple write operations.
### Operations Example
Example array structure for all supported operation types:
```php
[
[ 'deleteMany' => [ $filter ] ],
[ 'deleteOne' => [ $filter ] ],
[ 'insertOne' => [ $document ] ],
[ 'replaceOne' => [ $filter, $replacement, $options ] ],
[ 'updateMany' => [ $filter, $update, $options ] ],
[ 'updateOne' => [ $filter, $update, $options ] ],
]
```
Arguments correspond to the respective operation methods; however, the
"writeConcern" option is specified for the top-level bulk write operation
instead of each individual operation.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
ordered (boolean)
: If true, when an insert fails, return without performing the remaining
writes. If false, when a write fails, continue with the remaining writes, if
any. The default is true.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::deleteMany()](#deletemany)
* [MongoDB\Collection::deleteOne()](#deleteone)
* [MongoDB\Collection::insertOne()](#insertone)
* [MongoDB\Collection::replaceOne()](#replaceone)
* [MongoDB\Collection::updateMany()](#updatemany)
* [MongoDB\Collection::updateOne()](#updateone)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
---
## count()
```php
function count($filter = [], array $options = []): integer
```
Gets the number of documents matching the filter. Returns the number of matched
documents as an integer.
### Supported Options
hint (string|document)
: The index to use. If a document, it will be interpretted as an index
specification and a name will be generated.
limit (integer)
: The maximum number of documents to count.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
readConcern (MongoDB\Driver\ReadConcern)
: Read concern.
<br><br>
For servers < 3.2, this option is ignored as read concern is not available.
readPreference (MongoDB\Driver\ReadPreference)
: Read preference.
skip (integer)
: The number of documents to skip before returning the documents.
### See Also
* [MongoDB Manual: count command](http://docs.mongodb.org/manual/reference/command/count/)
---
## createIndex()
```php
function createIndex($key, array $options = []): string
```
Create a single index for the collection. Returns the name of the created index
as a string.
### Key Example
The `$key` argument must be a document containing one or more fields mapped to
an order or type. For example:
```
// Ascending index on the "username" field
$key = [ 'username' => 1 ];
// 2dsphere index on the "loc" field with a secondary index on "created_at"
$key = [ 'loc' => '2dsphere', 'created_at' => 1 ];
```
### Supported Options
Index options are documented in the [MongoDB manual][createIndexes].
[createIndexes]: https://docs.mongodb.org/manual/reference/command/createIndexes/
### See Also
* [MongoDB\Collection::createIndexes()](#createindexes)
* [Tutorial: Indexes](../tutorial/indexes.md)
* [MongoDB Manual: createIndexes command][createIndexes]
* [MongoDB Manual: Indexes][indexes]
[indexes]: https://docs.mongodb.org/manual/indexes/
---
## createIndexes()
``` ```
function createIndexes(array $indexes): string[]
```
Create one or more indexes for the collection. Returns the names of the created
indexes as an array of strings.
### Indexes Array
Each element in the `$indexes` array must have a "key" document, which contains
fields mapped to an order or type. Other options may follow. For example:
```php
[
// Create a unique index on the "username" field
[ 'key' => [ 'username' => 1 ], 'unique' => true ],
// Create a 2dsphere index on the "loc" field with a custom name
[ 'key' => [ 'loc' => '2dsphere' ], 'name' => 'geo' ],
]
```
If the "name" option is unspecified, a name will be generated from the "key"
document.
Index options are documented in the [MongoDB manual][createIndexes].
### See Also
* [MongoDB\Collection::createIndex()](#createindex)
* [Tutorial: Indexes](../tutorial/indexes.md)
* [MongoDB Manual: createIndexes command][createIndexes]
* [MongoDB Manual: Indexes][indexes]
---
## deleteMany()
```php
function deleteMany($filter, array $options = []): MongoDB\DeleteResult
```
Deletes all documents matching the filter.
### Supported Options
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::deleteOne()](#deleteone)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: delete command](https://docs.mongodb.org/manual/reference/command/delete/)
---
## deleteOne()
```php
function deleteOne($filter, array $options = []): MongoDB\DeleteResult
```
Deletes at most one document matching the filter.
### Supported Options
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::deleteMany()](#deletemany)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: delete command](https://docs.mongodb.org/manual/reference/command/delete/)
---
## distinct()
```php
function distinct($fieldName, $filter = [], array $options = []): mixed[]
```
Finds the distinct values for a specified field across the collection. Returns
an array of the distinct values.
### Supported Options
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
readConcern (MongoDB\Driver\ReadConcern)
: Read concern.
<br><br>
For servers < 3.2, this option is ignored as read concern is not available.
readPreference (MongoDB\Driver\ReadPreference)
: Read preference.
### See Also
* [MongoDB Manual: distinct command](https://docs.mongodb.org/manual/reference/command/distinct/)
---
## drop()
```php
function drop(array $options = []): array|object
```
Drop this collection. Returns the command result document.
### Supported Options
typeMap (array)
: Type map for BSON deserialization. This will be used for the returned
command result document.
### Example
The following example drops the "demo.zips" collection:
```
<?php
$collection = (new MongoDB\Client)->demo->zips; $collection = (new MongoDB\Client)->demo->zips;
$result = $collection->drop(); $result = $collection->drop();
var_dump($result); var_dump($result);
``` ```
...@@ -52,161 +415,555 @@ object(MongoDB\Model\BSONDocument)#11 (1) { ...@@ -52,161 +415,555 @@ object(MongoDB\Model\BSONDocument)#11 (1) {
} }
``` ```
## CRUD Operations ### See Also
CRUD is an acronym for Create, Read, Update, and Delete. The Collection class * [MongoDB\Database::dropCollection()](database.md#dropcollection)
implements MongoDB's cross-driver * [MongoDB Manual: drop command](https://docs.mongodb.org/manual/reference/command/drop/)
[CRUD specification](https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst),
which defines a common API for collection-level read and write methods.
Each method on the Collection class corresponds to a particular Operation class ---
within the library. The Collection's method merely merges in relevant options
(e.g. read preferences, type maps). Documentation for each CRUD method and its
options may be found in either the CRUD specification or those Operation
classes.
### API Differences from the Legacy Driver ## dropIndex()
```php
function dropIndex($indexName, array $options = []): array|object
```
The CRUD API has some notable differences from the legacy driver's Drop a single index in the collection. Returns the command result document.
[MongoCollection](http://php.net/mongocollection) class:
* `insert()` and `batchInsert()` have been renamed to `insertOne()` and ### Supported Options
`insertMany()`, respectively.
* `update()` has been split into `updateOne()`, `updateMany()`, and
`replaceOne()`.
* `remove()` has been split into `deleteOne()` and `deleteMany()`.
* `findAndModify()` has been split into `findOneAndDelete()`,
`findOneAndReplace()`, and `findOneAndUpdate()`.
* `save()`, which was syntactic sugar for an insert or upsert operation, has
been removed in favor of explicitly using `insertOne()` or `replaceOne()`
(with the `upsert` option).
* `aggregate()` and `aggregateCursor()` have been consolidated into a single
`aggregate()` method.
* A general-purpose `bulkWrite()` method replaces the legacy driver's
[`MongoWriteBatch`](http://php.net/mongowritebatch) class.
The general rule in designing our new API was that explicit method names were typeMap (array)
preferable to overloaded terms found in the old API. For instance, `save()` and : Type map for BSON deserialization. This will be used for the returned
`findAndModify()` had two or three very different modes of operation, depending command result document.
on their arguments. These new methods names also distinguish between
[updating specific fields](https://docs.mongodb.org/manual/tutorial/modify-documents/#update-specific-fields-in-a-document)
and [full-document replacement](https://docs.mongodb.org/manual/tutorial/modify-documents/#replace-the-document).
### Finding One or More Document(s) ### See Also
The `findOne()` and `find()` methods may be used to query for one or multiple * [MongoDB\Collection::dropIndexes()](#dropindexes)
documents. * [Tutorial: Indexes](../tutorial/indexes.md)
* [MongoDB Manual: dropIndexes command](http://docs.mongodb.org/manual/reference/command/dropIndexes/)
* [MongoDB Manual: Indexes][indexes]
---
## dropIndexes()
```php
function dropIndexes(array $options = []): array|object
``` ```
$collection = (new MongoDB\Client)->demo->zips;
$document = $collection->findOne(['_id' => '94301']); Drop all indexes in the collection. Returns the command result document.
var_dump($document);
### Supported Options
typeMap (array)
: Type map for BSON deserialization. This will be used for the returned
command result document.
### See Also
* [MongoDB\Collection::dropIndex()](#dropindex)
* [Tutorial: Indexes](../tutorial/indexes.md)
* [MongoDB Manual: dropIndexes command](http://docs.mongodb.org/manual/reference/command/dropIndexes/)
* [MongoDB Manual: Indexes][indexes]
---
## find()
```php
function find($filter = [], array $options = []): MongoDB\Driver\Cursor
``` ```
The above example would output something similar to: Finds documents matching the query. Returns a MongoDB\Driver\Cursor.
### Supported Options
allowPartialResults (boolean)
: Get partial results from a mongos if some shards are inaccessible (instead
of throwing an error).
batchSize (integer)
: The number of documents to return per batch.
comment (string)
: Attaches a comment to the query. If "$comment" also exists in the modifiers
document, this option will take precedence.
cursorType (enum)
: Indicates the type of cursor to use. Must be either NON_TAILABLE, TAILABLE,
or TAILABLE_AWAIT. The default is NON_TAILABLE.
limit (integer)
: The maximum number of documents to return.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run. If "$maxTimeMS" also
exists in the modifiers document, this option will take precedence.
modifiers (document)
: Meta-operators modifying the output or behavior of a query.
noCursorTimeout (boolean)
: The server normally times out idle cursors after an inactivity period (10
minutes) to prevent excess memory use. Set this option to prevent that.
oplogReplay (boolean)
: Internal replication use only. The driver should not set this.
projection (document)
: Limits the fields to return for the matching document.
readConcern (MongoDB\Driver\ReadConcern)
: Read concern.
<br><br>
For servers < 3.2, this option is ignored as read concern is not
available.
readPreference (MongoDB\Driver\ReadPreference)
: Read preference.
skip (integer)
: The number of documents to skip before returning.
sort (document)
: The order in which to return matching documents. If "$orderby" also exists
in the modifiers document, this option will take precedence.
typeMap (array)
: Type map for BSON deserialization. This will be applied to the returned
Cursor (it is not sent to the server).
### See Also
* [MongoDB\Collection::findOne()](#findOne)
* [MongoDB Manual: find command](http://docs.mongodb.org/manual/reference/command/find/)
---
## findOne()
```php
function findOne($filter = [], array $options = []): array|object
``` ```
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=> Finds a single document matching the query. Returns the matching document or
array(5) { null.
["_id"]=>
string(5) "94301" ### Supported Options
["city"]=>
string(9) "PALO ALTO" comment (string)
["loc"]=> : Attaches a comment to the query. If "$comment" also exists in the modifiers
object(MongoDB\Model\BSONArray)#12 (1) { document, this option will take precedence.
["storage":"ArrayObject":private]=>
array(2) { maxTimeMS (integer)
[0]=> : The maximum amount of time to allow the query to run. If "$maxTimeMS" also
float(-122.149685) exists in the modifiers document, this option will take precedence.
[1]=>
float(37.444324) modifiers (document)
} : Meta-operators modifying the output or behavior of a query.
}
["pop"]=> projection (document)
int(15965) : Limits the fields to return for the matching document.
["state"]=>
string(2) "CA" readConcern (MongoDB\Driver\ReadConcern)
} : Read concern.
} <br><br>
For servers < 3.2, this option is ignored as read concern is not available.
readPreference (MongoDB\Driver\ReadPreference)
: Read preference.
skip (integer)
: The number of documents to skip before returning.
sort (document)
: The order in which to return matching documents. If "$orderby" also exists
in the modifiers document, this option will take precedence.
typeMap (array)
: Type map for BSON deserialization.
### See Also
* [MongoDB\Collection::find()](#find)
* [MongoDB Manual: find command](http://docs.mongodb.org/manual/reference/command/find/)
---
## findOneAndDelete()
```php
function findOneAndDelete($filter, array $options = []): object|null
``` ```
The `find()` method returns a Finds a single document and deletes it, returning the original. The document to
[`MongoDB\Driver\Cursor`](http://php.net/mongodb-driver-cursor) object, which return may be null if no document matched the filter.
may be iterated upon to access all matched documents.
**Note:** BSON deserialization of the returned document does not yet support a
"typeMap" option; however, classes implementing
[MongoDB\BSON\Persistable][persistable] will still be deserialized according to
the [Persistence][persistence] specification.
### Supported Options
## Index Management maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
The Collection class implements MongoDB's cross-driver projection (document)
[Index Management](https://github.com/mongodb/specifications/blob/master/source/index-management.rst) : Limits the fields to return for the matching document.
and
[Enumerating Indexes](https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst)
specifications, which defines a common API for index-related methods.
### Creating Indexes sort (document)
: Determines which document the operation modifies if the query selects
multiple documents.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern. This option is only supported for server versions >= 3.2.
### See Also
* [MongoDB\Collection::findOneAndReplace()](#findoneandreplace)
* [MongoDB\Collection::findOneAndUpdate()](#findoneandupdate)
* [MongoDB Manual: findAndModify command][findandmodify]
---
## findOneAndReplace()
```php
function findOneAndReplace($filter, $replacement, array $options = []): object|null
``` ```
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->createIndex(['state' => 1]); Finds a single document and replaces it, returning either the original or the
var_dump($result); replaced document.
The document to return may be null if no document matched the filter. By
default, the original document is returned. Specify
`MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER` for the
"returnDocument" option to return the updated document.
**Note:** BSON deserialization of the returned document does not yet support a
"typeMap" option; however, classes implementing
[MongoDB\BSON\Persistable][persistable] will still be deserialized according to
the [Persistence][persistence] specification.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
projection (document)
: Limits the fields to return for the matching document.
returnDocument (enum)
: Whether to return the document before or after the update is applied. Must
be either `MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE` or
`MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER`. The default is
`MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE`.
sort (document)
: Determines which document the operation modifies if the query selects
multiple documents.
upsert (boolean)
: When true, a new document is created if no document matches the query. The
default is false.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern. This option is only supported for server versions >= 3.2.
### See Also
* [MongoDB\Collection::findOneAndDelete()](#findoneanddelete)
* [MongoDB\Collection::findOneAndUpdate()](#findoneandupdate)
* [MongoDB Manual: findAndModify command][findandmodify]
---
## findOneAndUpdate()
```php
function findOneAndUpdate($filter, $update, array $options = []): object|null
``` ```
The above example would output something similar to: Finds a single document and updates it, returning either the original or the
updated document.
The document to return may be null if no document matched the filter. By
default, the original document is returned. Specify
`MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER` for the
"returnDocument" option to return the updated document.
**Note:** BSON deserialization of the returned document does not yet support a
"typeMap" option; however, classes implementing
[MongoDB\BSON\Persistable][persistable] will still be deserialized according to
the [Persistence][persistence] specification.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
projection (document)
: Limits the fields to return for the matching document.
returnDocument (enum)
: Whether to return the document before or after the update is applied. Must
be either `MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_BEFORE` or
`MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER`. The default is
`MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_BEFORE`.
sort (document)
: Determines which document the operation modifies if the query selects
multiple documents.
upsert (boolean)
: When true, a new document is created if no document matches the query. The
default is false.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern. This option is only supported for server versions >= 3.2.
### See Also
* [MongoDB\Collection::findOneAndDelete()](#findoneanddelete)
* [MongoDB\Collection::findOneAndReplace()](#findoneandreplace)
* [MongoDB Manual: findAndModify command][findandmodify]
---
## getCollectionName()
```php
function getCollectionName(): string
``` ```
string(7) "state_1"
Return the collection name.
---
## getDatabaseName()
```php
function getDatabaseName(): string
``` ```
### Dropping Indexes Return the database name.
---
## getNamespace()
```php
function getNamespace(): string
``` ```
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->dropIndex('state_1'); Return the collection namespace.
var_dump($result);
### See Also
* [MongoDB Manual: namespace](https://docs.mongodb.org/manual/reference/glossary/#term-namespace)
---
## insertMany()
```php
function insertMany(array $documents, array $options = []): MongoDB\InsertManyResult
``` ```
The above example would output something similar to: Inserts multiple documents.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
ordered (boolean)
: If true, when an insert fails, return without performing the remaining
writes. If false, when a write fails, continue with the remaining writes, if
any. The default is true.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::insertOne()](#insertone)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: insert command](http://docs.mongodb.org/manual/reference/command/insert/)
---
## insertOne()
```php
function insertOne($document, array $options = []): MongoDB\InsertOneResult
``` ```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=> Inserts one document.
array(2) {
["nIndexesWas"]=> ### Supported Options
int(2)
["ok"]=> bypassDocumentValidation (boolean)
float(1) : If true, allows the write to opt out of document level validation.
}
} writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::insertMany()](#insertmany)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: insert command](http://docs.mongodb.org/manual/reference/command/insert/)
---
## listIndexes()
```php
function listIndexes(array $options = []): MongoDB\Model\IndexInfoIterator
``` ```
### Enumerating Indexes Returns information for all indexes for the collection. Elements in the returned
iterator will be MongoDB\Model\IndexInfo objects.
### Supported Options
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
### See Also
* [Tutorial: Indexes](../tutorial/indexes.md)
* [MongoDB Manual: listIndexes command](http://docs.mongodb.org/manual/reference/command/listIndexes/)
* [MongoDB Manual: Indexes][indexes]
* [MongoDB Specification: Enumerating Collections](https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst)
---
## replaceOne()
```php
function replaceOne($filter, $replacement, array $options = []): MongoDB\UpdateResult
``` ```
/* listIndexes() returns an iterator of MongoDB\Model\IndexInfo objects */
$collection = (new MongoDB\Client)->demo->zips;
foreach ($collection->listIndexes() as $indexInfo) { Replaces at most one document matching the filter.
var_dump($indexInfo);
} ### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
upsert (boolean)
: When true, a new document is created if no document matches the query. The
default is false.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::updateMany()](#updatemany)
* [MongoDB\Collection::updateOne()](#updateone)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: update command](http://docs.mongodb.org/manual/reference/command/update/)
---
## updateMany()
```php
function updateMany($filter, $update, array $options = []): MongoDB\UpdateResult
``` ```
The above example would output something similar to: Updates all documents matching the filter.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
upsert (boolean)
: When true, a new document is created if no document matches the query. The
default is false.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::replaceOne()](#replaceone)
* [MongoDB\Collection::updateOne()](#updateone)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: update command](http://docs.mongodb.org/manual/reference/command/update/)
---
## updateOne()
```php
function updateOne($filter, $update, array $options = []): MongoDB\UpdateResult
``` ```
object(MongoDB\Model\IndexInfo)#4 (4) {
["v"]=> Updates at most one document matching the filter.
int(1)
["key"]=> ### Supported Options
array(1) {
["_id"]=> bypassDocumentValidation (boolean)
int(1) : If true, allows the write to opt out of document level validation.
}
["name"]=> upsert (boolean)
string(4) "_id_" : When true, a new document is created if no document matches the query. The
["ns"]=> default is false.
string(9) "demo.zips"
} writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::replaceOne()](#replaceone)
* [MongoDB\Collection::updateMany()](#updatemany)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: update command](http://docs.mongodb.org/manual/reference/command/update/)
---
## withOptions()
```php
function withOptions(array $options = []): MongoDB\Collection
``` ```
Returns a clone of this Collection with different options.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for collection operations. Defaults to the
Manager's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for collection operations. Defaults to
the Manager's read preference.
typeMap (array)
: Default type map for cursors and BSON documents.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for collection operations. Defaults to the
Manager's write concern.
### See Also
* [MongoDB\Collection::__construct()](#__construct)
# MongoDB\Database # MongoDB\Database
`MongoDB\Database` provides methods for common operations on a database, such The MongoDB\Database class provides methods for common operations on a database,
as creating, enumerating, and dropping collections. such as executing commands and managing collections.
A Database may be constructed directly (using the extension's Manager class) or A Database may be constructed directly (using the extension's Manager class) or
selected from the library's Client class. It supports the following options: selected from the library's [Client](client.md) class. It supports the following
options:
* [readConcern](http://php.net/mongodb-driver-readconcern) * [readConcern](http://php.net/mongodb-driver-readconcern)
* [readPreference](http://php.net/mongodb-driver-readpreference) * [readPreference](http://php.net/mongodb-driver-readpreference)
...@@ -14,97 +15,192 @@ selected from the library's Client class. It supports the following options: ...@@ -14,97 +15,192 @@ selected from the library's Client class. It supports the following options:
If any options are omitted, they will be inherited from the Manager constructor If any options are omitted, they will be inherited from the Manager constructor
argument or object from which the Database was selected. argument or object from which the Database was selected.
Operations within the Database class (e.g. `command()`) will generally inherit Operations within the Database class (e.g. [command()](#command)) will generally
the Database's options. inherit the Database's options.
### Selecting Collections ---
The Database class provides methods for creating Collection instances (using its ## __construct()
internal Manager instance). When selecting a Collection, the child will inherit
options (e.g. read preference, type map) from the Database. New options may also
be provided to the `selectCollection()` method.
```php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, array $options = [])
``` ```
$db = (new MongoDB\Client)->demo;
/* Select the "users" collection */ If the Database is constructed explicitly, any omitted options will be inherited
$collection = $db->selectCollection('users'); from the Manager object. If the Database is selected from a [Client](client.md)
object, options will be inherited from that object.
/* selectCollection() also takes an options array, which can override any ### Supported Options
* options inherited from the Database. */
$collection = $client->selectCollection('users', [ readConcern (MongoDB\Driver\ReadConcern)
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY), : The default read concern to use for database operations and selected
]); collections. Defaults to the Manager's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for database operations and selected
collections. Defaults to the Manager's read preference.
typeMap (array)
: Default type map for cursors and BSON documents.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for database operations and selected
collections. Defaults to the Manager's write concern.
### See Also
* [MongoDB\Database::withOptions()](#withoptions)
---
/* The property accessor may also be used to select a collection without ## __get()
* specifying additional options. PHP's complex syntax may be used for selecting
* collection whose names contain special characters (e.g. "."). */ ```php
$collection = $db->users; function __get($collectionName): MongoDB\Collection
$collection = $db->{'system.profile'};
``` ```
## Database-level Operations Select a collection within this database.
The Collection will inherit options (e.g. read preference, type map) from the
Database object. Use [selectCollection()](#selectcollection) to override any
options.
**Note:** collections whose names contain special characters (e.g. ".") may be
selected with complex syntax (e.g. `$database->{"system.profile"}`) or
[selectCollection()](#selectcollection).
The Database class has methods for database-level operations, such as dropping ### Example
the database, executing a command, or managing the database's collections.
### Dropping the Database The following example selects the "demo.users" and "demo.system.profile"
collections:
``` ```
<?php
$db = (new MongoDB\Client)->demo; $db = (new MongoDB\Client)->demo;
$result = $db->drop(); $users = $db->users;
var_dump($result); $systemProfile = $db->{'system.profile'};
``` ```
The above example would output something similar to: ### See Also
* [MongoDB\Database::selectCollection()](#selectcollection)
* [PHP Manual: Property Overloading](http://php.net/oop5.overloading#object.get)
---
## command()
```php
function function command($command, array $options = []): MongoDB\Driver\Cursor
``` ```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=> Execute a command on this database.
array(2) {
["dropped"]=> ### Supported Options
string(4) "demo"
["ok"]=> readPreference (MongoDB\Driver\ReadPreference)
float(1) : The read preference to use when executing the command. This may be used when
} issuing the command to a replica set or mongos node to ensure that the
} driver sets the wire protocol accordingly or adds the read preference to the
command document, respectively.
typeMap (array)
: Type map for BSON deserialization. This will be applied to the returned
Cursor (it is not sent to the server).
### See Also
* [Tutorial: Database Commands](../tutorial/commands.md)
* [MongoDB Manual: Database Commands](https://docs.mongodb.org/manual/reference/command/)
## createCollection
```php
function createCollection($collectionName, array $options = []): array|object
``` ```
### Executing a Command Create a new collection explicitly. Returns the command result document.
While the library provides helpers for some common database commands, it is far MongoDB already creates collections implicitly when they are first referenced in
from an [exhaustive list](https://docs.mongodb.org/manual/reference/command/). commands (e.g. inserting a document into a new collection); however, collections
The following example demonstrates how the may also be explicitly created with specific options. This is useful for
[createUser](https://docs.mongodb.org/manual/reference/command/createUser/) creating [capped collections][capped], enabling
command might be invoked: [document validation][validation], or supplying storage engine options.
[capped]: https://docs.mongodb.org/manual/core/capped-collections/
[validation]: https://docs.mongodb.org/manual/core/document-validation/
### Supported Options
autoIndexId (boolean)
: Specify false to disable the automatic creation of an index on the _id
field. For replica sets, this option cannot be false. The default is true.
capped (boolean)
: Specify true to create a capped collection. If set, the size option must
also be specified. The default is false.
flags (integer)
: Options for the MMAPv1 storage engine only. Must be a bitwise combination
`MongoDB\Operation\CreateCollection::USE_POWER_OF_2_SIZES` and
`MongoDB\Operation\CreateCollection::NO_PADDING`. The default is
`MongoDB\Operation\CreateCollection::USE_POWER_OF_2_SIZES`.
indexOptionDefaults (document)
: Default configuration for indexes when creating the collection.
max (integer)
: The maximum number of documents allowed in the capped collection. The size
option takes precedence over this limit.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
size (integer)
: The maximum number of bytes for a capped collection.
storageEngine (document)
: Storage engine options.
typeMap (array)
: Type map for BSON deserialization. This will only be used for the returned
command result document.
validationAction (string)
: Validation action.
validationLevel (string)
: Validation level.
validator (document)
: Validation rules or expressions.
### Example
The following example creates the "demo.users" collection with a custom
[document validator][validation] (available in MongoDB 3.2+):
``` ```
<?php
$db = (new MongoDB\Client)->demo; $db = (new MongoDB\Client)->demo;
/* Define a command document for creating a new database user */ $result = $db->createCollection('users', [
$createUserCmd = [ 'validator' => [
'createUser' => 'username', 'username' => ['$type' => 'string'],
'pwd' => 'password', 'email' => ['$regex' => '@mongodb\.com$'],
'roles' => [ 'readWrite' ], ],
];
/* It doesn't hurt to specify an explicit read preference for the command, in
* case the Database was created with a different read preference. This isn't
* required for other command helpers, as the library knows which commands might
* require a primary; however, the Database::command() method is generic. */
$cursor = $db->command($createUserCmd, [
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY),
]); ]);
/* The command result will be the first and only document in the cursor */ var_dump($result);
var_dump($cursor->toArray()[0]);
``` ```
The above example would output something similar to: The above example would output something similar to:
``` ```
object(MongoDB\Model\BSONDocument)#8 (1) { object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=> ["storage":"ArrayObject":private]=>
array(1) { array(1) {
["ok"]=> ["ok"]=>
...@@ -113,30 +209,35 @@ object(MongoDB\Model\BSONDocument)#8 (1) { ...@@ -113,30 +209,35 @@ object(MongoDB\Model\BSONDocument)#8 (1) {
} }
``` ```
## Collection Management ### See Also
The Database class has several methods for managing collections. * [MongoDB Manual: create command](http://docs.mongodb.org/manual/reference/command/create/)
### Creating Collections ---
MongoDB already creates collections implicitly when they are first referenced in ## drop
commands (e.g. inserting a document into a new collection); however, collections
may also be explicitly created with specific options. This is useful for ```php
creating function drop(array $options = []): array|object
[capped collections](https://docs.mongodb.org/manual/core/capped-collections/), ```
enabling
[document validation](https://docs.mongodb.org/manual/core/document-validation/), Drop this database. Returns the command result document.
or supplying storage engine options.
### Supported Options
typeMap (array)
: Type map for BSON deserialization. This will only be used for the returned
command result document.
### Example
The following example drops the "demo" database:
``` ```
$db = (new MongoDB\Client)->demo; $db = (new MongoDB\Client)->demo;
$result = $db->createCollection('users', [ $result = $db->drop();
'validator' => [
'username' => ['$type' => 'string'],
'email' => ['$regex' => '@mongodb\.com$'],
],
]);
var_dump($result); var_dump($result);
``` ```
...@@ -145,19 +246,47 @@ The above example would output something similar to: ...@@ -145,19 +246,47 @@ The above example would output something similar to:
``` ```
object(MongoDB\Model\BSONDocument)#11 (1) { object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=> ["storage":"ArrayObject":private]=>
array(1) { array(2) {
["dropped"]=>
string(4) "demo"
["ok"]=> ["ok"]=>
float(1) float(1)
} }
} }
``` ```
### Dropping Collections ### See Also
* [MongoDB\Client::dropDatabase()](client.md#dropdatabase)
* [MongoDB Manual: dropDatabase command](http://docs.mongodb.org/manual/reference/command/dropDatabase/)
---
## dropCollection
```php
function dropCollection($collectionName, array $options = []): array|object
```
Drop a collection within this database. Returns the command result document.
### Supported Options
typeMap (array)
: Type map for BSON deserialization. This will only be used for the returned
command result document.
### Example
The following example drops the "demo.users" collection:
``` ```
<?php
$db = (new MongoDB\Client)->demo; $db = (new MongoDB\Client)->demo;
$result = $db->dropCollection('users'); $result = $db->dropCollection('users');
var_dump($result); var_dump($result);
``` ```
...@@ -177,15 +306,49 @@ object(MongoDB\Model\BSONDocument)#11 (1) { ...@@ -177,15 +306,49 @@ object(MongoDB\Model\BSONDocument)#11 (1) {
} }
``` ```
### Enumerating Collections ### See Also
* [MongoDB\Collection::drop()](collection.md#drop)
* [MongoDB Manual: drop command](http://docs.mongodb.org/manual/reference/command/drop/)
The Database class implements MongoDB's ---
[Enumerating Collections specification](https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst).
## getDatabaseName()
```php
function getDatabaseName(): string
```
Return the database name.
---
## listCollections()
```php
function listCollections(array $options = []): MongoDB\Model\CollectionInfoIterator
``` ```
Returns information for all collections in this database. Elements in the
returned iterator will be MongoDB\Model\CollectionInfo objects.
### Supported Options
filter (document)
: Query by which to filter collections.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
### Example
The following example lists all collections in the "demo" database:
```
<?php
$db = (new MongoDB\Client)->demo; $db = (new MongoDB\Client)->demo;
/* listCollections() returns an iterator of MongoDB\Model\CollectionInfo objects */
foreach ($db->listCollections() as $collectionInfo) { foreach ($db->listCollections() as $collectionInfo) {
var_dump($collectionInfo); var_dump($collectionInfo);
} }
...@@ -213,3 +376,103 @@ object(MongoDB\Model\CollectionInfo)#13 (2) { ...@@ -213,3 +376,103 @@ object(MongoDB\Model\CollectionInfo)#13 (2) {
} }
} }
``` ```
### See Also
* [MongoDB Manual: listCollections command](http://docs.mongodb.org/manual/reference/command/listCollections/)
* [MongoDB Specification: Enumerating Collections](https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst)
---
## selectCollection()
```php
function selectCollection($collectionName, array $options = []): MongoDB\Collection
```
Select a collection within this database.
The Collection will inherit options (e.g. read preference, type map) from the
Database object unless otherwise specified.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for collection operations. Defaults to the
Database's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for collection operations. Defaults to
the Database's read preference.
typeMap (array)
: Default type map for cursors and BSON documents. Defaults to the Database's
type map.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for collection operations. Defaults to the
Database's write concern.
### Example
The following example selects the "demo.users" collection:
```
<?php
$db = (new MongoDB\Client)->demo;
$collection = $db->selectCollection('users');
```
The following examples selects the "demo.users" collection with a custom read
preference:
```
<?php
$db = (new MongoDB\Client)->demo;
$collection = $db->selectCollection(
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
```
### See Also
* [MongoDB\Collection::__construct()](collection.md#__construct)
* [MongoDB\Database::__get()](#__get)
---
## withOptions()
```php
function withOptions(array $options = []): MongoDB\Database
```
Returns a clone of this database with different options.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for database operations and selected
collections. Defaults to the Manager's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for database operations and selected
collections. Defaults to the Manager's read preference.
typeMap (array)
: Default type map for cursors and BSON documents.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for database operations and selected
collections. Defaults to the Manager's write concern.
### See Also
* [MongoDB\Database::__construct()](#__construct)
# BSON Conversion
## Deserialization
By default, the library returns BSON documents and arrays as
MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray objects, respectively.
Both of those classes extend PHP's [ArrayObject][arrayobject] class and
implement the driver's [MongoDB\BSON\Serializable][serializable] and
[MongoDB\BSON\Unserializable][unserializable] interfaces.
[arrayobject]: http://php.net/arrayobject
[serializable]: http://php.net/mongodb-bson-serializable
[unserializable]: http://php.net/mongodb-bson-unserializable
## Type Maps
Most methods that read data from MongoDB support a "typeMap" option, which
allows control over how BSON is converted to PHP. Additionally, the
[MongoDB\Client][client], [MongoDB\Database][database], and
[MongoDB\Collection][collection] classes accept a "typeMap" option, which will
apply to any supporting methods and selected classes by default.
[client]: ../classes/client.md
[database]: ../classes/database.md
[collection]: ../classes/collection.md
The [MongoDB\Client][client], [MongoDB\Database][database], and
[MongoDB\Collection][collection] classes use the following type map by default:
```php
[
'array' => 'MongoDB\Model\BSONArray',
'document' => 'MongoDB\Model\BSONDocument',
'root' => 'MongoDB\Model\BSONDocument',
]
```
## Persistable Classes
Classes implementing [MongoDB\BSON\Persistable][persistable] will be serialized
and deserialized according to the [Persistence][persistence] specification. This
behavior occurs by default in the [driver][ext-mongodb] and does not require use
of the "typeMap" option.
[persistable]: http://php.net/mongodb-bson-persistable
[persistence]: http://php.net/manual/en/mongodb.persistence.php
[ext-mongodb]: https://php.net/mongodb
Given the following class definition:
```
<?php
class Person implements MongoDB\BSON\Persistable
{
private $id;
private $name;
private $createdAt;
public function __construct($name)
{
$this->id = new MongoDB\BSON\ObjectID;
$this->name = (string) $name;
// Get current time in milliseconds since the epoch
$msec = floor(microtime(true) * 1000);
$this->createdAt = new MongoDB\BSON\UTCDateTime($msec);
}
function bsonSerialize()
{
return [
'_id' => $this->id,
'name' => $this->name,
'createdAt' => $this->createdAt,
];
}
function bsonUnserialize(array $data)
{
$this->id = $data['_id'];
$this->name = $data['name'];
$this->createdAt = $data['createdAt'];
}
}
```
The following example constructs a Person object, inserts it into the database,
and reads it back as an object of the same type (without the use of the
"typeMap" option):
```
<?php
$collection = (new MongoDB\Client)->demo->persons;
$result = $collection->insertOne(new Person('Bob'));
$person = $collection->findOne(['_id' => $result->getInsertedId()]);
var_dump($person);
```
The above example would output something similar to:
```
object(Person)#18 (3) {
["id":"Person":private]=>
object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=>
string(24) "56fad2c36118fd2e9820cfc1"
}
["name":"Person":private]=>
string(3) "Bob"
["createdAt":"Person":private]=>
object(MongoDB\BSON\UTCDateTime)#17 (1) {
["milliseconds"]=>
int(1459278531218)
}
}
```
The same document in the MongoDB shell might display as:
```
> db.persons.findOne()
{
"_id" : ObjectId("56fad2c36118fd2e9820cfc1"),
"__pclass" : BinData(128,"UGVyc29u"),
"name" : "Bob",
"createdAt" : ISODate("2016-03-29T19:08:51.218Z")
}
```
**Note:** [MongoDB\BSON\Persistable][persistable] may only be used for root and
embedded BSON documents; BSON arrays are not supported.
## Emulating the Legacy Driver
The legacy [mongo extension][ext-mongo] returned both BSON documents and
arrays as PHP arrays. While PHP arrays are convenient to work with, this
behavior was problematic for several reasons:
[ext-mongo]: http://php.net/mongo
* Different BSON types could deserialize to the same PHP value (e.g.
`{"0": "foo"}` and `["foo"]`), which made it impossible to infer the
original BSON type.
* Numerically indexed PHP arrays would be serialized as BSON documents if there
was a gap in their key sequence. Such gaps were easily (and inadvertently)
caused by unsetting a key to remove an element and forgetting to reindex the
array.
The libary's MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray classes
address these concerns by preserving the BSON type information during
serialization and deserialization; however, some users may still prefer the
legacy behavior. If desired, the following "typeMap" option can be used to have
the library return everything as a PHP array:
```
<?php
$client = new MongoDB\Client(
null,
[],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
);
$document = $client->demo->zips->findOne(
['_id' => '94301'],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
);
var_dump($document);
```
The above example would output something similar to:
```
array(5) {
["_id"]=>
string(5) "94301"
["city"]=>
string(9) "PALO ALTO"
["loc"]=>
array(2) {
[0]=>
float(-122.149685)
[1]=>
float(37.444324)
}
["pop"]=>
int(15965)
["state"]=>
string(2) "CA"
}
```
# Database Commands
While the library provides helpers for some common database commands, it is far
from an [exhaustive list][command-list]. This page will demonstrate how to
execute arbitrary commands on the MongoDB server via the
[Database::command()][command] method and access their results.
[command-list]: https://docs.mongodb.org/manual/reference/command/
[command]: ../classes/database.md#command
## Single Result Documents
The [command()][command] method always returns a
[MongoDB\Driver\Cursor][cursor]. Unless otherwise stated in the MongoDB
documentation, command responses are returned as a single document. Reading such
a result will require iterating on the cursor and accessing the first (and only)
document, like so:
[cursor]: http://php.net/mongodb-driver-cursor
```
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command(['ping' => 1]);
var_dump($cursor->toArray()[0]);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#2 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
```
## Iterable Results as a Command Cursor
Some commands, such as [listCollections][listcollections], return their results
via an iterable command cursor. In this case, the returned
[MongoDB\Driver\Cursor][cursor] may be iterated in the same manner as one might
do with a [Collection::find()][find] query, like so:
[listcollections]: http://docs.mongodb.org/manual/reference/command/listCollections/
[find]: ../classes/collection.md#find
```
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command(['listCollections' => 1]);
foreach ($cursor as $collection) {
echo $collection['name'], "\n";
}
```
The above example would output something similar to:
```
persons
posts
zips
```
**Note:** at the protocol level, commands that support a cursor actually return
a single result document with the essential ingredients for constructing the
command cursor (i.e. the cursor's ID, namespace, and first batch of results);
however, the driver's [executeCommand()][executecommand] method already detects
such a result and constructs the iterable command cursor for us.
[executecommand]: http://php.net/manual/en/mongodb-driver-manager.executecommand.php
## Specifying a Read Preference
Some commands, such as [createUser][createUser], can only be executed on a
primary server. Command helpers in the library, such as
[Database::drop()][drop], know to apply their own read preference if necessary;
however, [command()][command] is a generic method and has no special knowledge.
It defaults to the read preference of the Database object on which it is
invoked. In such cases, it can be helpful to explicitly specify the correct read
preference, like so:
[createUser]: https://docs.mongodb.org/manual/reference/command/createUser/
[drop]: ../classes/database.md#drop
```
<?php
$db = (new MongoDB\Client)->demo;
$cursor = $db->command(
[
'createUser' => 'username',
'pwd' => 'password',
'roles' => ['readWrite'],
],
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY),
]
);
var_dump($cursor->toArray()[0]);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
```
# CRUD Operations
CRUD is an acronym for Create, Read, Update, and Delete. These operations may be
performed via the [MongoDB\Collection][collection] class, which implements
MongoDB's cross-driver [CRUD specification][crud-spec]. This page will
demonstrate how to insert, query, update, and delete documents using the
library. A general introduction to CRUD operations in MongoDB may be found in
the [MongoDB Manual][crud].
[collection]: ../classes/collection.md
[crud-spec]: https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst
[crud]: https://docs.mongodb.org/manual/crud/
## Finding One Document
The [findOne()][findone] method returns the first matched document, or null if
no document was matched.
[findone]: ../classes/collection.md#findone
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$document = $collection->findOne(['_id' => '94301']);
var_dump($document);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
array(5) {
["_id"]=>
string(5) "94301"
["city"]=>
string(9) "PALO ALTO"
["loc"]=>
object(MongoDB\Model\BSONArray)#12 (1) {
["storage":"ArrayObject":private]=>
array(2) {
[0]=>
float(-122.149685)
[1]=>
float(37.444324)
}
}
["pop"]=>
int(15965)
["state"]=>
string(2) "CA"
}
}
```
## Finding Many Documents
The [find()][find] method returns a [MongoDB\Driver\Cursor][cursor] object,
which may be iterated upon to access all matched documents. The following
example queries for all zip codes in a given city:
[find]: ../classes/collection.md#find
[cursor]: http://php.net/mongodb-driver-cursor
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);
foreach ($cursor as $document) {
echo $document['_id'], "\n";
}
```
The above example would output something similar to:
```
07302
07304
07305
07306
07307
07310
```
## Query Projection
Queries may include a [projection][projection] to include or exclude specific
fields in the returned documents. The following example selects only the
population field for the zip code:
[projection]: https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$document = $collection->findOne(
['_id' => '10011'],
['projection' => ['pop => 1']]
);
var_dump($document);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["_id"]=>
string(5) "10011"
["pop"]=>
int(46560)
}
}
```
**Note:** the "_id" field is included by default unless explicitly excluded.
## Limit, Sort, and Skip Options
In addition to criteria, queries may take options to limit, sort, and skip
returned documents. The following example queries for the five most populous
zip codes in the United States:
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$cursor = $collection->find(
[],
[
'limit' => 5,
'sort' => ['pop' => -1],
]
);
foreach ($cursor as $document) {
echo $document['_id'], "\n";
}
```
The above example would output something similar to:
```
60623: CHICAGO, IL
11226: BROOKLYN, NY
10021: NEW YORK, NY
10025: NEW YORK, NY
90201: BELL GARDENS, CA
```
## Aggregation
The [Aggregation Framework][aggregation] may be used to issue complex queries
that filter, transform, and group collection data. The [aggregate()][aggregate]
method returns a [Traversable][traversable] object, which may be iterated
upon to access the results of an aggregation pipeline.
[aggregation]: https://docs.mongodb.org/manual/core/aggregation-pipeline/
[aggregate]: ../classes/collection.md#aggregate
[traversable]: http://php.net/traversable
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$cursor = $collection->aggregate([
['$group' => ['_id' => '$state', 'count' => ['$sum' => 1]]],
['$sort' => ['count' => -1]],
['$limit' => 5],
]);
foreach ($cursor as $state) {
printf("%s has %d zip codes\n", $state['_id'], $state['count']);
}
```
The above example would output something similar to:
```
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
```
**Note:** [aggregate()][aggregate] is documented as returning a
[Traversable][traversable] object because the [aggregate][aggregate-cmd] command
may return its results inline (i.e. a single result document's array field,
which the library will package as a PHP iterator) or via a command cursor (i.e.
[MongoDB\Driver\Cursor][cursor]).
[aggregate-cmd]: (http://docs.mongodb.org/manual/reference/command/aggregate/)
# Example Data # Example Data
Some examples in this documentation use example data fixtures from Some examples in this documentation use example data fixtures from
[zips.json](http://media.mongodb.org/zips.json). This is a dataset comprised of [zips.json][zips]. This is a dataset comprised of United States postal codes,
United States postal codes, populations, and geographic locations. populations, and geographic locations.
Importing the dataset into MongoDB can be done in several ways. The following Importing the dataset into MongoDB can be done in several ways. The following
example uses [PHP driver](http://php.net/mongodb) (i.e. `mongodb` extension). example uses [mongodb extension][ext-mongodb]:
[zips]: http://media.mongodb.org/zips.json
[ext-mongodb]: http://php.net/mongodb
``` ```
<?php
$file = 'http://media.mongodb.org/zips.json'; $file = 'http://media.mongodb.org/zips.json';
$zips = file($file, FILE_IGNORE_NEW_LINES); $zips = file($file, FILE_IGNORE_NEW_LINES);
...@@ -30,10 +35,11 @@ Executing this script should yield the following output: ...@@ -30,10 +35,11 @@ Executing this script should yield the following output:
Inserted 29353 documents Inserted 29353 documents
``` ```
You may also import the dataset using the You may also import the dataset using the [mongoimport][mongoimport] command,
[`mongoimport`](http://docs.mongodb.org/manual/reference/program/mongoimport/) which is included with MongoDB:
command, which is included with MongoDB:
``` [mongoimport]: http://docs.mongodb.org/manual/reference/program/mongoimport/
```bash
$ mongoimport --db demo --collection zips --file zips.json --drop $ mongoimport --db demo --collection zips --file zips.json --drop
``` ```
# Indexes
Indexes may be managed via the [MongoDB\Collection][collection] class, which
implements MongoDB's cross-driver [Index Management][index-spec] and
[Enumerating Indexes][enum-spec] specifications. This page will demonstrate how
to create, list, and drop indexes using the library. General information on how
indexes work in MongoDB may be found in the [MongoDB manual][indexes].
[collection]: ../classes/collection.md
[index-spec]: https://github.com/mongodb/specifications/blob/master/source/index-management.rst
[enum-spec]: https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst
[indexes]: https://docs.mongodb.org/manual/indexes/
## Creating Indexes
Indexes may be created via the [createIndex()][createindex] and
[createIndexes()][createindexes] methods. The following example creates an
ascending index on the "state" field:
[createindex]: ../classes/collection.md#createindex
[createindexes]: ../classes/collection.md#createindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->createIndex(['state' => 1]);
var_dump($result);
```
Creating an index will return its name, which is automatically generated from
its specification (i.e. fields and orderings). The above example would output
something similar to:
```
string(7) "state_1"
```
### Enumerating Indexes
Information about indexes in a collection may be obtained via the
[listIndexes()][listindexes] method, which returns an iterator of
MongoDB\Model\IndexInfo objects. The following example lists all indexes in the
"demo.zips" collection:
[listindexes]: ../classes/collection.md#listindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
foreach ($collection->listIndexes() as $indexInfo) {
var_dump($indexInfo);
}
```
The above example would output something similar to:
```
object(MongoDB\Model\IndexInfo)#10 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["_id"]=>
int(1)
}
["name"]=>
string(4) "_id_"
["ns"]=>
string(9) "demo.zips"
}
object(MongoDB\Model\IndexInfo)#13 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["state"]=>
int(1)
}
["name"]=>
string(7) "state_1"
["ns"]=>
string(9) "demo.zips"
}
```
### Dropping Indexes
Indexes may be dropped via the [dropIndex()][dropindex] and
[dropIndexes()][dropindexes] methods. The following example drops a single index
by its name:
[dropindex]: ../classes/collection.md#dropindex
[dropindexes]: ../classes/collection.md#dropindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->dropIndex('state_1');
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
```
# Upgrade Guide
The MongoDB PHP Library and underlying [mongodb extension][ext-mongodb] have
notable API differences from the legacy [mongo extension][ext-mongo]. This page
will attempt to summarize those differences for the benefit of those upgrading
rom the legacy driver.
Additionally, a community-developed [mongo-php-adapter][adapter] library exists,
which implements the [mongo extension][ext-mongo] API using this library and the
new driver. While this adapter library is not officially supported by MongoDB,
it does bear mentioning.
[ext-mongo]: http://php.net/mongo
[ext-mongodb]: http://php.net/mongodb
[adapter]: https://github.com/alcaeus/mongo-php-adapter
## Collection API
This library's [MongoDB\Collection][collection] class implements MongoDB's
cross-driver [CRUD][crud-spec] and [Index Management][index-spec]
specifications. Although some method names have changed in accordance with the
new specifications, the new class provides the same functionality as the legacy
driver's [MongoCollection][mongocollection] class with some notable exceptions.
[collection]: classes/collection.md
[crud-spec]: https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst
[index-spec]: https://github.com/mongodb/specifications/blob/master/source/index-management.rst
[mongocollection]: http://php.net/mongocollection
### Old and New Methods
| [MongoCollection][mongocollection] | [MongoDB\Collection][collection] |
| --- | --- |
| [aggregate()](http://php.net/manual/en/mongocollection.aggregate.php) | [aggregate()](classes/collection.md#aggregate) |
| [aggregateCursor()](http://php.net/manual/en/mongocollection.aggregatecursor.php) | [aggregate()](classes/collection.md#aggregate) |
| [batchInsert()](http://php.net/manual/en/mongocollection.batchinsert.php) | [insertMany()](classes/collection.md#insertmany) |
| [count()](http://php.net/manual/en/mongocollection.count.php) | [count()](classes/collection.md#count) |
| [createDBRef()](http://php.net/manual/en/mongocollection.createdbref.php) | Not yet implemented ([PHPLIB-24][jira-dbref]) |
| [createIndex()](http://php.net/manual/en/mongocollection.createindex.php) | [createIndex()](classes/collection.md#createindex) |
| [deleteIndex()](http://php.net/manual/en/mongocollection.deleteindex.php) | [dropIndex()](classes/collection.md#dropindex) |
| [deleteIndexes()](http://php.net/manual/en/mongocollection.deleteindexes.php) | [dropIndexes()](classes/collection.md#dropindexes) |
| [drop()](http://php.net/manual/en/mongocollection.drop.php) | [drop()](classes/collection.md#drop) |
| [distinct()](http://php.net/manual/en/mongocollection.distinct.php) | [distinct()](classes/collection.md#distinct) |
| [ensureIndex()](http://php.net/manual/en/mongocollection.ensureindex.php) | [createIndex()](classes/collection.md#createindex) |
| [find()](http://php.net/manual/en/mongocollection.find.php) | [find()](classes/collection.md#find) |
| [findAndModify()](http://php.net/manual/en/mongocollection.findandmodify.php) | [findOneAndDelete()](classes/collection.md#findoneanddelete), [findOneAndReplace()](classes/collection.md#findoneandreplace), and [findOneAndUpdate()](classes/collection.md#findoneandupdate) |
| [findOne()](http://php.net/manual/en/mongocollection.findone.php) | [findOne()](classes/collection.md#findone) |
| [getDBRef()](http://php.net/manual/en/mongocollection.getdbref.php) | Not yet implemented ([PHPLIB-24][jira-dbref]) |
| [getIndexInfo()](http://php.net/manual/en/mongocollection.getindexinfo.php) | [listIndexes()](classes/collection.md#listindexes) |
| [getName()](http://php.net/manual/en/mongocollection.getname.php) | [getCollectionName()](classes/collection.md#getcollectionname) |
| [getReadPreference()](http://php.net/manual/en/mongocollection.getreadpreference.php) | Not implemented |
| [getSlaveOkay()](http://php.net/manual/en/mongocollection.getslaveokay.php) | Not implemented |
| [getWriteConcern()](http://php.net/manual/en/mongocollection.getwriteconcern.php) | Not implemented |
| [group()](http://php.net/manual/en/mongocollection.group.php) | Not yet implemented ([PHPLIB-177][jira-group]). Use [Database::command()](classes/database.md#command) for now. |
| [insert()](http://php.net/manual/en/mongocollection.insert.php) | [insertOne()](classes/collection.md#insertone) |
| [parallelCollectionScan()](http://php.net/manual/en/mongocollection.parallelcollectionscan.php) | Not implemented |
| [remove()](http://php.net/manual/en/mongocollection.remove.php) | [deleteMany()](classes/collection.md#deleteMany) and [deleteOne()](classes/collection.md#deleteone) |
| [save()](http://php.net/manual/en/mongocollection.save.php) | [insertOne()](classes/collection.md#insertone) or [replaceOne()](classes/collection.md#replaceone) with "upsert" option |
| [setReadPreference()](http://php.net/manual/en/mongocollection.setreadpreference.php) | Not implemented. Use [withOptions()](classes/collection.md#withoptions). |
| [setSlaveOkay()](http://php.net/manual/en/mongocollection.getslaveokay.php) | Not implemented |
| [setWriteConcern()](http://php.net/manual/en/mongocollection.setwriteconcern.php) | Not implemented. Use [withOptions()](classes/collection.md#withoptions). |
| [update()](http://php.net/manual/en/mongocollection.update.php) | [replaceOne()](classes/collection.md#replaceone), [updateMany()](classes/collection.md#updatemany), and [updateOne()](classes/collection.md#updateone) |
| [validate()](http://php.net/manual/en/mongocollection.validate.php) | Not implemented |
[jira-group]: https://jira.mongodb.org/browse/PHPLIB-177
[jira-dbref]: https://jira.mongodb.org/browse/PHPLIB-24
A guiding principle in designing the new APIs was that explicit method names
are preferable to overloaded terms found in the old API. For instance,
[MongoCollection::save()][save] and
[MongoCollection::findAndModify()][findandmodify] have very different modes of
operation, depending on their arguments. Methods were also split to distinguish
between [updating specific fields][update] and
[full-document replacement][replace].
[save]: http://php.net/manual/en/mongocollection.save.php
[findandmodify]: http://php.net/manual/en/mongocollection.findandmodify.php
[update]: https://docs.mongodb.org/manual/tutorial/modify-documents/#update-specific-fields-in-a-document
[replace]: https://docs.mongodb.org/manual/tutorial/modify-documents/#replace-the-document
### Group Command Helper
[MongoDB\Collection][collection] does not yet have a helper method for the
[group][group] command; however, that is planned in [PHPLIB-177][jira-group].
The following example demonstrates how to execute a group command using
[Database::command()](classes/database.md#command):
```php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'group' => [
'ns' => 'collection_name',
'key' => ['field_name' => 1],
'initial' => ['total' => 0],
'$reduce' => new MongoDB\BSON\Javascript('...'),
],
]);
$resultDocument = $cursor->toArray()[0];
```
[group]: https://docs.mongodb.org/manual/reference/command/group/
### MapReduce Command Helper
[MongoDB\Collection][collection] does not yet have a helper method for the
[mapReduce][mapReduce] command; however, that is planned in
[PHPLIB-53][jira-mapreduce]. The following example demonstrates how to execute a
mapReduce command using [Database::command()](classes/database.md#command):
```php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'mapReduce' => 'collection_name',
'map' => new MongoDB\BSON\Javascript('...'),
'reduce' => new MongoDB\BSON\Javascript('...'),
'out' => 'output_collection_name',
]);
$resultDocument = $cursor->toArray()[0];
```
[mapReduce]: https://docs.mongodb.org/manual/reference/command/mapReduce/
[jira-mapreduce]: https://jira.mongodb.org/browse/PHPLIB-53
### DBRef Helpers
[MongoDB\Collection][collection] does not yet have helper methods for working
with [DBRef][dbref] objects; however, that is planned in
[PHPLIB-24][jira-dbref].
[dbref]: https://docs.mongodb.org/manual/reference/database-references/#dbrefs
### MongoCollection::save() Removed
[MongoCollection::save()][save], which was syntactic sugar for an insert or
upsert operation, has been removed in favor of explicitly using
[insertOne()](classes/collection.md#insertone) or
[replaceOne()](classes/collection.md#replaceone) (with the "upsert" option).
![save() flowchart](img/save-flowchart.png)
While the [save()][save] method does have its uses for interactive environments,
such as the mongo shell, it was intentionally excluded from the
[CRUD][crud-spec] specification for language drivers. Generally, application
code should know if the document has an identifier and be able to explicitly
insert or replace the document and handle the returned InsertResult or
UpdateResult, respectively. This also helps avoid inadvertent and potentially
dangerous [full-document replacements][replace].
### MongoWriteBatch
The legacy driver's [MongoWriteBatch][batch] classes have been replaced with a
general-purpose [bulkWrite()](classes/collection.md#bulkwrite) method. Whereas
the legacy driver only allowed bulk operations of the same time, the new method
allows operations to be mixed (e.g. inserts, updates, and deletes).
[batch]: http://php.net/manual/en/class.mongowritebatch.php
...@@ -7,13 +7,21 @@ theme: readthedocs ...@@ -7,13 +7,21 @@ theme: readthedocs
pages: pages:
- 'Home': 'index.md' - 'Home': 'index.md'
- 'Getting Started': 'getting-started.md' - 'Getting Started': 'getting-started.md'
- 'Example Data': 'example-data.md' - 'Upgrade Guide': 'upgrade-guide.md'
- Tutorial:
- 'BSON Conversion': 'tutorial/bson.md'
- 'CRUD Operations': 'tutorial/crud.md'
- 'Database Commands': 'tutorial/commands.md'
- 'Indexes': 'tutorial/indexes.md'
- 'Example Data': 'tutorial/example-data.md'
- Classes: - Classes:
- 'Client': 'classes/client.md' - 'Client': 'classes/client.md'
- 'Database': 'classes/database.md' - 'Database': 'classes/database.md'
- 'Collection': 'classes/collection.md' - 'Collection': 'classes/collection.md'
markdown_extensions: markdown_extensions:
- def_list
- fenced_code
- smarty - smarty
- toc: - toc:
permalink: true permalink: true
...@@ -76,7 +76,7 @@ class Client ...@@ -76,7 +76,7 @@ class Client
/** /**
* Select a database. * Select a database.
* *
* Note: collections whose names contain special characters (e.g. "-") may * Note: databases whose names contain special characters (e.g. "-") may
* be selected with complex syntax (e.g. $client->{"that-database"}) or * be selected with complex syntax (e.g. $client->{"that-database"}) or
* {@link selectDatabase()}. * {@link selectDatabase()}.
* *
......
...@@ -446,7 +446,7 @@ class Collection ...@@ -446,7 +446,7 @@ class Collection
* @see http://docs.mongodb.org/manual/core/read-operations-introduction/ * @see http://docs.mongodb.org/manual/core/read-operations-introduction/
* @param array|object $filter Query by which to filter documents * @param array|object $filter Query by which to filter documents
* @param array $options Additional options * @param array $options Additional options
* @return object|null * @return array|object|null
*/ */
public function findOne($filter = [], array $options = []) public function findOne($filter = [], array $options = [])
{ {
...@@ -471,7 +471,7 @@ class Collection ...@@ -471,7 +471,7 @@ class Collection
/** /**
* Finds a single document and deletes it, returning the original. * Finds a single document and deletes it, returning the original.
* *
* The document to return may be null. * The document to return may be null if no document matched the filter.
* *
* Note: BSON deserialization of the returned document does not yet support * Note: BSON deserialization of the returned document does not yet support
* a custom type map (depends on: https://jira.mongodb.org/browse/PHPC-314). * a custom type map (depends on: https://jira.mongodb.org/browse/PHPC-314).
...@@ -499,9 +499,10 @@ class Collection ...@@ -499,9 +499,10 @@ class Collection
* Finds a single document and replaces it, returning either the original or * Finds a single document and replaces it, returning either the original or
* the replaced document. * the replaced document.
* *
* The document to return may be null. By default, the original document is * The document to return may be null if no document matched the filter. By
* returned. Specify FindOneAndReplace::RETURN_DOCUMENT_AFTER for the * default, the original document is returned. Specify
* "returnDocument" option to return the updated document. * FindOneAndReplace::RETURN_DOCUMENT_AFTER for the "returnDocument" option
* to return the updated document.
* *
* Note: BSON deserialization of the returned document does not yet support * Note: BSON deserialization of the returned document does not yet support
* a custom type map (depends on: https://jira.mongodb.org/browse/PHPC-314). * a custom type map (depends on: https://jira.mongodb.org/browse/PHPC-314).
...@@ -530,9 +531,10 @@ class Collection ...@@ -530,9 +531,10 @@ class Collection
* Finds a single document and updates it, returning either the original or * Finds a single document and updates it, returning either the original or
* the updated document. * the updated document.
* *
* The document to return may be null. By default, the original document is * The document to return may be null if no document matched the filter. By
* returned. Specify FindOneAndUpdate::RETURN_DOCUMENT_AFTER for the * default, the original document is returned. Specify
* "returnDocument" option to return the updated document. * FindOneAndUpdate::RETURN_DOCUMENT_AFTER for the "returnDocument" option
* to return the updated document.
* *
* Note: BSON deserialization of the returned document does not yet support * Note: BSON deserialization of the returned document does not yet support
* a custom type map (depends on: https://jira.mongodb.org/browse/PHPC-314). * a custom type map (depends on: https://jira.mongodb.org/browse/PHPC-314).
...@@ -580,7 +582,7 @@ class Collection ...@@ -580,7 +582,7 @@ class Collection
/** /**
* Return the collection namespace. * Return the collection namespace.
* *
* @see http://docs.mongodb.org/manual/faq/developers/#faq-dev-namespace * @see https://docs.mongodb.org/manual/reference/glossary/#term-namespace
* @return string * @return string
*/ */
public function getNamespace() public function getNamespace()
...@@ -691,7 +693,7 @@ class Collection ...@@ -691,7 +693,7 @@ class Collection
/** /**
* Updates at most one document matching the filter. * Updates at most one document matching the filter.
* *
* @see ReplaceOne::__construct() for supported options * @see UpdateOne::__construct() for supported options
* @see http://docs.mongodb.org/manual/reference/command/update/ * @see http://docs.mongodb.org/manual/reference/command/update/
* @param array|object $filter Query by which to filter documents * @param array|object $filter Query by which to filter documents
* @param array|object $update Update to apply to the matched document * @param array|object $update Update to apply to the matched document
......
...@@ -166,7 +166,7 @@ class Database ...@@ -166,7 +166,7 @@ class Database
* @see CreateCollection::__construct() for supported options * @see CreateCollection::__construct() for supported options
* @param string $collectionName * @param string $collectionName
* @param array $options * @param array $options
* @return object Command result document * @return array|object Command result document
*/ */
public function createCollection($collectionName, array $options = []) public function createCollection($collectionName, array $options = [])
{ {
......
...@@ -36,8 +36,8 @@ class BulkWrite implements Executable ...@@ -36,8 +36,8 @@ class BulkWrite implements Executable
* Example array structure for all supported operation types: * Example array structure for all supported operation types:
* *
* [ * [
* [ 'deleteOne' => [ $filter ] ],
* [ 'deleteMany' => [ $filter ] ], * [ 'deleteMany' => [ $filter ] ],
* [ 'deleteOne' => [ $filter ] ],
* [ 'insertOne' => [ $document ] ], * [ 'insertOne' => [ $document ] ],
* [ 'replaceOne' => [ $filter, $replacement, $options ] ], * [ 'replaceOne' => [ $filter, $replacement, $options ] ],
* [ 'updateMany' => [ $filter, $update, $options ] ], * [ 'updateMany' => [ $filter, $update, $options ] ],
...@@ -46,7 +46,7 @@ class BulkWrite implements Executable ...@@ -46,7 +46,7 @@ class BulkWrite implements Executable
* *
* Arguments correspond to the respective Operation classes; however, the * Arguments correspond to the respective Operation classes; however, the
* writeConcern option is specified for the top-level bulk write operation * writeConcern option is specified for the top-level bulk write operation
* instead of each individual operations. * instead of each individual operation.
* *
* Supported options for replaceOne, updateMany, and updateOne operations: * Supported options for replaceOne, updateMany, and updateOne operations:
* *
......
...@@ -35,8 +35,9 @@ class CreateCollection implements Executable ...@@ -35,8 +35,9 @@ class CreateCollection implements Executable
* the size option must also be specified. The default is false. * the size option must also be specified. The default is false.
* *
* * flags (integer): Options for the MMAPv1 storage engine only. Must be a * * flags (integer): Options for the MMAPv1 storage engine only. Must be a
* bitwise combination USE_POWER_OF_2_SIZES and NO_PADDING. The default * bitwise combination CreateCollection::USE_POWER_OF_2_SIZES and
* is USE_POWER_OF_2_SIZES. * CreateCollection::NO_PADDING. The default is
* CreateCollection::USE_POWER_OF_2_SIZES.
* *
* * indexOptionDefaults (document): Default configuration for indexes when * * indexOptionDefaults (document): Default configuration for indexes when
* creating the collection. * creating the collection.
...@@ -127,7 +128,7 @@ class CreateCollection implements Executable ...@@ -127,7 +128,7 @@ class CreateCollection implements Executable
* *
* @see Executable::execute() * @see Executable::execute()
* @param Server $server * @param Server $server
* @return object Command result document * @return array|object Command result document
*/ */
public function execute(Server $server) public function execute(Server $server)
{ {
......
...@@ -22,6 +22,11 @@ class DropDatabase implements Executable ...@@ -22,6 +22,11 @@ class DropDatabase implements Executable
/** /**
* Constructs a dropDatabase command. * Constructs a dropDatabase command.
* *
* Supported options:
*
* * typeMap (array): Type map for BSON deserialization. This will be used
* for the returned command result document.
*
* @param string $databaseName Database name * @param string $databaseName Database name
* @param array $options Command options * @param array $options Command options
*/ */
......
...@@ -23,6 +23,11 @@ class DropIndexes implements Executable ...@@ -23,6 +23,11 @@ class DropIndexes implements Executable
/** /**
* Constructs a dropIndexes command. * Constructs a dropIndexes command.
* *
* Supported options:
*
* * typeMap (array): Type map for BSON deserialization. This will be used
* for the returned command result document.
*
* @param string $databaseName Database name * @param string $databaseName Database name
* @param string $collectionName Collection name * @param string $collectionName Collection name
* @param string $indexName Index name (use "*" to drop all indexes) * @param string $indexName Index name (use "*" to drop all indexes)
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
namespace MongoDB\Operation; namespace MongoDB\Operation;
use MongoDB\Driver\Cursor;
use MongoDB\Driver\Query; use MongoDB\Driver\Query;
use MongoDB\Driver\ReadConcern; use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\ReadPreference; use MongoDB\Driver\ReadPreference;
......
...@@ -74,7 +74,7 @@ class FindOne implements Executable ...@@ -74,7 +74,7 @@ class FindOne implements Executable
* *
* @see Executable::execute() * @see Executable::execute()
* @param Server $server * @param Server $server
* @return object|null * @return array|object|null
*/ */
public function execute(Server $server) public function execute(Server $server)
{ {
......
...@@ -35,8 +35,10 @@ class FindOneAndReplace implements Executable ...@@ -35,8 +35,10 @@ class FindOneAndReplace implements Executable
* document. * document.
* *
* * returnDocument (enum): Whether to return the document before or after * * returnDocument (enum): Whether to return the document before or after
* the update is applied. Must be either RETURN_DOCUMENT_BEFORE or * the update is applied. Must be either
* RETURN_DOCUMENT_AFTER. The default is RETURN_DOCUMENT_BEFORE. * FindOneAndReplace::RETURN_DOCUMENT_BEFORE or
* FindOneAndReplace::RETURN_DOCUMENT_AFTER. The default is
* FindOneAndReplace::RETURN_DOCUMENT_BEFORE.
* *
* * sort (document): Determines which document the operation modifies if * * sort (document): Determines which document the operation modifies if
* the query selects multiple documents. * the query selects multiple documents.
......
...@@ -35,8 +35,10 @@ class FindOneAndUpdate implements Executable ...@@ -35,8 +35,10 @@ class FindOneAndUpdate implements Executable
* document. * document.
* *
* * returnDocument (enum): Whether to return the document before or after * * returnDocument (enum): Whether to return the document before or after
* the update is applied. Must be either RETURN_DOCUMENT_BEFORE or * the update is applied. Must be either
* RETURN_DOCUMENT_AFTER. The default is RETURN_DOCUMENT_BEFORE. * FindOneAndUpdate::RETURN_DOCUMENT_BEFORE or
* FindOneAndUpdate::RETURN_DOCUMENT_AFTER. The default is
* FindOneAndUpdate::RETURN_DOCUMENT_BEFORE.
* *
* * sort (document): Determines which document the operation modifies if * * sort (document): Determines which document the operation modifies if
* the query selects multiple documents. * the query selects multiple documents.
......
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