Commit ab7aba10 authored by Allison Moore's avatar Allison Moore Committed by Jeremy Mikola

Remove Markdown documentation (i.e gh-pages)

parent 0b68ed61
# MongoDB\Client
The MongoDB\Client class serves as an entry point for the library. It is the
preferred class for connecting to a MongoDB server or cluster of servers and
serves as a gateway for accessing individual databases and collections. It is
analogous to the driver's [MongoDB\Driver\Manager][manager] class, which it
composes.
[manager]: http://php.net/mongodb-driver-manager
---
## __construct()
```php
function __construct($uri = 'mongodb://localhost:27017', array $uriOptions = [], array $driverOptions = [])
```
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(
'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet',
[
'readPreference' => 'secondaryPreferred'
]
);
```
By default, the library will unserialize BSON documents and arrays as
MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray objects, respectively.
The following example demonstrates how to have the library unserialize
everything as a PHP array, as was done in the legacy
[mongo extension][ext-mongo]:
[ext-mongo]: http://php.net/mongo
```
<?php
$client = new MongoDB\Client(
null,
[],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
);
```
### See Also
* [MongoDB\Driver\Manager::__construct()][manager-construct]
* [MongoDB Manual: Connection String][connection-string]
---
## __get()
```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;
$demo = $client->demo;
$anotherApp = $client->{'another-app'};
```
### See Also
* [MongoDB\Client::selectDatabase()](#selectdatabase)
* [PHP Manual: Property Overloading](http://php.net/oop5.overloading#object.get)
---
## dropDatabase
```php
function dropDatabase($databaseName, array $options = []): array|object
```
Drop a 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" database:
```
<?php
$client = new MongoDB\Client;
$result = $client->dropDatabase('demo');
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dropped"]=>
string(4) "demo"
["ok"]=>
float(1)
}
}
```
### 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;
foreach ($client->listDatabases() as $databaseInfo) {
var_dump($databaseInfo);
}
```
The above example would output something similar to:
```
object(MongoDB\Model\DatabaseInfo)#4 (3) {
["name"]=>
string(5) "local"
["sizeOnDisk"]=>
float(65536)
["empty"]=>
bool(false)
}
object(MongoDB\Model\DatabaseInfo)#7 (3) {
["name"]=>
string(4) "test"
["sizeOnDisk"]=>
float(32768)
["empty"]=>
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
The MongoDB\Collection class provides methods for common operations on a
collection and its documents. This includes, but is not limited to, CRUD
operations (e.g. inserting, querying, counting) and managing indexes.
A Collection may be constructed directly (using the extension's Manager class),
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)
* [readPreference](http://php.net/mongodb-driver-readpreference)
* [typeMap](http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps)
* [writeConcern](http://php.net/mongodb-driver-writeconcern)
Operations within the Collection class (e.g. [find()](#find),
[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.
[findandmodify]: http://docs.mongodb.org/manual/reference/command/findAndModify/
---
## __construct()
```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;
$result = $collection->drop();
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["ns"]=>
string(9) "demo.zips"
["nIndexesWas"]=>
int(1)
["ok"]=>
float(1)
}
}
```
### See Also
* [MongoDB\Database::dropCollection()](database.md#dropcollection)
* [MongoDB Manual: drop command](https://docs.mongodb.org/manual/reference/command/drop/)
---
## dropIndex()
```php
function dropIndex($indexName, array $options = []): array|object
```
Drop a single index in the 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.
### See Also
* [MongoDB\Collection::dropIndexes()](#dropindexes)
* [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
```
Drop all indexes in the 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.
### 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
```
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
```
Finds a single document matching the query. Returns the matching document or
null.
### Supported Options
comment (string)
: Attaches a comment to the query. If "$comment" also exists in the modifiers
document, this option will take precedence.
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.
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.
### 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
```
Finds a single document and deletes it, returning the original. The document to
return may be null if no document matched the filter.
**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
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
projection (document)
: Limits the fields to return for the matching document.
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
```
Finds a single document and replaces it, returning either the original or the
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
```
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
```
Return the collection name.
---
## getDatabaseName()
```php
function getDatabaseName(): string
```
Return the database name.
---
## getNamespace()
```php
function getNamespace(): string
```
Return the collection namespace.
### See Also
* [MongoDB Manual: namespace](https://docs.mongodb.org/manual/reference/glossary/#term-namespace)
---
## insertMany()
```php
function insertMany(array $documents, array $options = []): MongoDB\InsertManyResult
```
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
```
Inserts one document.
### Supported Options
bypassDocumentValidation (boolean)
: 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
```
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
```
Replaces at most one document 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::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
```
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
```
Updates at most one document 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::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
The MongoDB\Database class provides methods for common operations on a database,
such as executing commands and managing collections.
A Database may be constructed directly (using the extension's Manager class) or
selected from the library's [Client](client.md) class. It supports the following
options:
* [readConcern](http://php.net/mongodb-driver-readconcern)
* [readPreference](http://php.net/mongodb-driver-readpreference)
* [typeMap](http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps)
* [writeConcern](http://php.net/mongodb-driver-writeconcern)
If any options are omitted, they will be inherited from the Manager constructor
argument or object from which the Database was selected.
Operations within the Database class (e.g. [command()](#command)) will generally
inherit the Database's options.
---
## __construct()
```php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, array $options = [])
```
If the Database is constructed explicitly, any omitted options will be inherited
from the Manager object. If the Database is selected from a [Client](client.md)
object, options will be inherited from that object.
### 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::withOptions()](#withoptions)
---
## __get()
```php
function __get($collectionName): MongoDB\Collection
```
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).
### Example
The following example selects the "demo.users" and "demo.system.profile"
collections:
```
<?php
$db = (new MongoDB\Client)->demo;
$users = $db->users;
$systemProfile = $db->{'system.profile'};
```
### 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
```
Execute a command on this database.
### Supported Options
readPreference (MongoDB\Driver\ReadPreference)
: 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
```
Create a new collection explicitly. Returns the command result document.
MongoDB already creates collections implicitly when they are first referenced in
commands (e.g. inserting a document into a new collection); however, collections
may also be explicitly created with specific options. This is useful for
creating [capped collections][capped], enabling
[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;
$result = $db->createCollection('users', [
'validator' => [
'username' => ['$type' => 'string'],
'email' => ['$regex' => '@mongodb\.com$'],
],
]);
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
```
### See Also
* [MongoDB Manual: create command](http://docs.mongodb.org/manual/reference/command/create/)
---
## drop
```php
function drop(array $options = []): array|object
```
Drop 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" database:
```
$db = (new MongoDB\Client)->demo;
$result = $db->drop();
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dropped"]=>
string(4) "demo"
["ok"]=>
float(1)
}
}
```
### 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;
$result = $db->dropCollection('users');
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["ns"]=>
string(10) "demo.users"
["nIndexesWas"]=>
int(1)
["ok"]=>
float(1)
}
}
```
### See Also
* [MongoDB\Collection::drop()](collection.md#drop)
* [MongoDB Manual: drop command](http://docs.mongodb.org/manual/reference/command/drop/)
---
## 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;
foreach ($db->listCollections() as $collectionInfo) {
var_dump($collectionInfo);
}
```
The above example would output something similar to:
```
object(MongoDB\Model\CollectionInfo)#8 (2) {
["name"]=>
string(5) "users"
["options"]=>
array(0) {
}
}
object(MongoDB\Model\CollectionInfo)#13 (2) {
["name"]=>
string(14) "system.profile"
["options"]=>
array(2) {
["capped"]=>
bool(true)
["size"]=>
int(1048576)
}
}
```
### 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)
# Getting Started
### Requirements
Since this library is only a high-level abstraction for the driver, it requires
that the `mongodb` extension be installed:
```
$ pecl install mongodb
$ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
```
Instructions for installing the `mongodb` extension on HHVM may be found in the
[Installation with HHVM](http://php.net/manual/en/mongodb.tutorial.install.hhvm.php)
article in the driver documentation.
### Installation
The preferred method of installing this library is with
[Composer](https://getcomposer.org/) by running the following from your project
root:
```
$ composer require "mongodb/mongodb=^1.0.0"
```
While not recommended, the package may also be installed manually via source
tarballs attached to
[GitHub releases](https://github.com/mongodb/mongo-php-library/releases).
### Configure Autoloading
Once the library is installed, ensure that your application includes Composer's
autoloader.
```
// This path should point to Composer's autoloader
require_once __DIR__ . "/vendor/autoload.php";
```
More information on this setup may be found in Composer's
[autoloading documentation](https://getcomposer.org/doc/01-basic-usage.md#autoloading).
If you have installed the package manually (e.g. from a source tarball), you
will likely need configure autoloading manually:
* Map the top-level `MongoDB\` namespace to the `src/` directory using your
preferred autoloader implementation
* Manually require the `src/functions.php` file, since PHP does not yet support
function autoloading
# MongoDB PHP Library
This library provides a high-level abstraction around the lower-level
[PHP driver](https://php.net/mongodb) (i.e. the `mongodb` extension).
While the extension provides a limited API for executing commands, queries, and
write operations, this library implements an API similar to that of the
[legacy PHP driver](http://php.net/manual/en/book.mongo.php). It contains
abstractions for client, database, and collection objects, and provides methods
for CRUD operations and common commands (e.g. index and collection management).
Support for GridFS is forthcoming.
If you are developing an application with MongoDB, you should consider using
this library, or another high-level abstraction, instead of the extension alone.
For additional information about this library and the ``mongodb`` extension,
see the [Architecture Overview](http://php.net/manual/en/mongodb.overview.php)
article in the driver documentation. [Derick Rethans](http://derickrethans.nl/)
has also written a series of blog posts entitled *New MongoDB Drivers for PHP
and HHVM*:
* [Part One: History](http://derickrethans.nl/new-drivers.html)
* [Part Two: Architecture](http://derickrethans.nl/new-drivers-part2.html)
* [Part Three: Cursor Behaviour](https://derickrethans.nl/new-drivers-part3-cursor.html)
## API Documentation
Generated API documentation for the library is available at:
* [http://mongodb.github.io/mongo-php-library/api](http://mongodb.github.io/mongo-php-library/api)
## MongoDB Tutorial
If you are a new MongoDB user, these links should help you become more familiar
with MongoDB and introduce some of the concepts and terms you will encounter in
this documentation:
* [Introduction to CRUD operations in MongoDB](http://docs.mongodb.org/manual/core/crud-introduction/)
* [What is a MongoDB document?](http://docs.mongodb.org/manual/core/document/)
* [MongoDB's *dot notation* for accessing document properties](http://docs.mongodb.org/manual/core/document/#dot-notation)
* [ObjectId: MongoDB's document identifier](http://docs.mongodb.org/manual/reference/object-id/)
# 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/
This page covers the following common use cases:
* Querying for [one](#finding-one-document) or [many](#finding-many-documents)
documents at a time
* [Projecting](#query-projection) fields in a query
* Applying [limit, sort, and skip options](#limit-sort-and-skip-options) to a
query
* Inserting [one](#inserting-one-document) or [many](#inserting-many-documents)
documents at a time
* Updating [one](#updating-one-document) or [many](#updating-many-documents)
documents at a time
* [Replacing](#replacing-a-document) a document
* [Upserting](#upserting-a-document) a document
* Deleting [one](#deleting-one-document) or [many](#deleting-many-documents)
documents at a time
* [Aggregating](#aggregating-documents) documents
Note that the use of arrays to express documents in the following examples was
done for simplicity. The driver will also accept instances of stdClass or
[MongoDB\BSON\Serializable][serializable]) for these arguments (e.g. query
filters, inserted documents, update documents).
[serializable]: http://php.net/mongodb-bson-serializable
Documents destined for database storage (e.g. insert documents, replacement
documents, embedded documents included in an update operation) may also be
instances of [MongoDB\BSON\Persistable][persistable]. See
[Persistable Classes][persistable-classes] for more information.
[persistable]: http://php.net/mongodb-bson-persistable
[persistable-classes]: bson.md#persistable-classes
## 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
```
## Inserting One Document
The [insertOne()][insertone] method may be used to insert a single document.
This method returns an instance of `MongoDB\InsertOneResult`, which may be used
to access the ID of the inserted document. Note that if a document does not
contain an `_id` field at the time of insertion, the driver will generate a
`MongoDB\BSON\ObjectID` to use as its ID.
[insertone]: ../classes/collection.md#insertone
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$insertOneResult = $collection->insertOne(['name' => 'Bob']);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
```
The above example would output something similar to:
```
Inserted 1 document(s)
object(MongoDB\BSON\ObjectID)#10 (1) {
["oid"]=>
string(24) "5750905b6118fd170565aa81"
}
```
The following example inserts a document with an ID. Note that if an ID is not
unique for the collection, the insert will fail due to a duplicate key error.
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
```
The above example would output:
```
Inserted 1 document(s)
int(1)
```
## Inserting Many Documents
The [insertMany()][insertmany] method may be used to insert multiple documents
at a time. This method returns an instance of `MongoDB\InsertManyResult`, which
may be used to access the IDs of the inserted documents.
[insertmany]: ../classes/collection.md#insertmany
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$insertManyResult = $collection->insertMany([
['name' => 'Bob'],
['_id' => 1, 'name' => 'Alice'],
]);
printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());
var_dump($insertManyResult->getInsertedIds());
```
The above example would output something similar to:
```
Inserted 2 document(s)
array(2) {
[0]=>
object(MongoDB\BSON\ObjectID)#10 (1) {
["oid"]=>
string(24) "5750927b6118fd1ed64eb141"
}
[1]=>
int(1)
}
```
## Updating One Document
The [updateOne()][updateone] method may be used to update a single document
matching a filter. This method returns an instance of `MongoDB\UpdateResult`,
which may be used to access statistics about the update operation.
[updateone]: ../classes/collection.md#updateone
This method has two required parameters: a query filter and an update document.
The query filter is similar to what might be provided to [find()][find]. The
update document consists of one or more [update operators][updateops].
[updateops]: https://docs.mongodb.com/manual/reference/operator/update/
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$updateResult = $collection->updateOne(
['state' => 'ny'],
['$set' => ['country' => 'us']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
```
The above example would output something similar to:
```
Matched 1 document(s)
Modified 1 document(s)
```
Note that it is possible for a document to match the filter but not be modified
by an update:
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$updateResult = $collection->updateOne(
['name' => 'Bob'],
['$set' => ['state' => 'ny']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
```
The above example would output something similar to:
```
Matched 1 document(s)
Modified 0 document(s)
```
## Updating Many Documents
The [updateMany()][updatemany] method may be used to update multiple documents
at a time. This method returns an instance of `MongoDB\UpdateResult`, which may
be used to access statistics about the update operation.
[updatemany]: ../classes/collection.md#updatemany
This method has two required parameters: a query filter and an update document.
The query filter is similar to what might be provided to [find()][find]. The
update document consists of one or more [update operators][updateops].
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny', 'country' => 'us']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$collection->insertOne(['name' => 'Sam', 'state' => 'ny']);
$updateResult = $collection->updateMany(
['state' => 'ny'],
['$set' => ['country' => 'us']]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
```
The above example would output something similar to:
```
Matched 3 document(s)
Modified 2 document(s)
```
## Replacing a Document
The [replaceOne()][replaceone] method may be used to replace a single document
matching a filter. This method returns an instance of `MongoDB\UpdateResult`,
which may be used to access statistics about the replacement operation.
[replaceone]: ../classes/collection.md#replaceone
This method has two required parameters: a query filter and a replacement
document. The query filter is similar to what might be provided to
[find()][find]. The replacement document will be used to overwrite the matched
document (excluding its ID, which is immutable) and must not contain
[update operators][updateops].
Note that the very nature of a replacement operation makes it easy to
inadvertently overwrite or delete fields in a document. When possible, users
should consider updating individual fields with [updateOne()][updateone] or
[updateMany()][updatemany].
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$updateResult = $collection->replaceOne(
['name' => 'Bob'],
['name' => 'Robert', 'state' => 'ca']
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
```
The above example would output something similar to:
```
Matched 1 document(s)
Modified 1 document(s)
```
Note that it is possible for a document to match the filter but not be modified
by a replacement (i.e. the matched document and replacement may be the same).
## Upserting a Document
An upsert is a variation of an update or replace operation, whereby a new
document is inserted if the query filter does not match an existing document.
An upsert may be specified via the `upsert` option for [updateOne()][updateone],
[updateMany()][updatemany], or [replaceOne()][replaceone]. The logic by which
the inserted document is created is discussed in the [MongoDB manual][upsert].
[upsert]: https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-parameter
If a document has been upserted, its ID will be accessible via
`MongoDB\UpdateResult::getUpsertedId()`.
The following example demonstrates an upsert via [updateOne()][updateone]:
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$updateResult = $collection->updateOne(
['name' => 'Bob'],
['$set' => ['state' => 'ny']],
['upsert' => true]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
var_dump($collection->findOne(['_id' => $updateResult->getUpsertedId()]));
```
The above example would output something similar to:
```
Matched 0 document(s)
Modified 0 document(s)
object(MongoDB\Model\BSONDocument)#16 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=>
string(24) "57509c4406d7241dad86e7c3"
}
["name"]=>
string(3) "Bob"
["state"]=>
string(2) "ny"
}
}
```
The following example demonstrates an upsert via [replaceOne()][replaceone]:
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$updateResult = $collection->replaceOne(
['name' => 'Bob'],
['name' => 'Alice', 'state' => 'ny'],
['upsert' => true]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
var_dump($collection->findOne(['_id' => $updateResult->getUpsertedId()]));
```
The above example would output something similar to:
```
Matched 0 document(s)
Modified 0 document(s)
object(MongoDB\Model\BSONDocument)#16 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=>
string(24) "57509c6606d7241dad86e7c4"
}
["name"]=>
string(5) "Alice"
["state"]=>
string(2) "ny"
}
}
```
## Deleting One Document
The [deleteOne()][deleteone] method may be used to delete a single document
matching a filter. This method returns an instance of `MongoDB\DeleteResult`,
which may be used to access statistics about the delete operation.
[deleteone]: ../classes/collection.md#deleteone
This method has two required parameters: a query filter. The query filter is
similar to what might be provided to [find()][find].
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$deleteResult = $collection->deleteOne(['state' => 'ny']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
```
The above example would output something similar to:
```
Deleted 1 document(s)
```
## Deleting Many Documents
The [deleteMany()][deletemany] method may be used to delete multiple documents
at a time. This method returns an instance of `MongoDB\DeleteResult`, which may
be used to access statistics about the delete operation.
[deletemany]: ../classes/collection.md#deletemany
This method has two required parameters: a query filter. The query filter is
similar to what might be provided to [find()][find].
```
<?php
$collection = (new MongoDB\Client)->demo->users;
$collection->drop();
$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$deleteResult = $collection->deleteMany(['state' => 'ny']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
```
The above example would output something similar to:
```
Deleted 2 document(s)
```
## Aggregating Documents
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
Some examples in this documentation use example data fixtures from
[zips.json][zips]. This is a dataset comprised of United States postal codes,
populations, and geographic locations.
Importing the dataset into MongoDB can be done in several ways. The following
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';
$zips = file($file, FILE_IGNORE_NEW_LINES);
$bulk = new MongoDB\Driver\BulkWrite;
foreach ($zips as $string) {
$document = json_decode($string);
$bulk->insert($document);
}
$manager = new MongoDB\Driver\Manager('mongodb://localhost');
$result = $manager->executeBulkWrite('demo.zips', $bulk);
printf("Inserted %d documents\n", $result->getInsertedCount());
```
Executing this script should yield the following output:
```
Inserted 29353 documents
```
You may also import the dataset using the [mongoimport][mongoimport] 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
```
# 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
from 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()][command]:
[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()][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()][insertone] or [replaceOne()][replaceone] (with the "upsert"
option).
[insertone]: classes/collection.md#insertone
[replaceone]: classes/collection.md#replaceone
![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].
### Accessing IDs of Inserted Documents
In the legacy driver, [MongoCollection::insert()][insert],
[MongoCollection::batchInsert()][batchinsert], and
[MongoCollection::save()][save] (when inserting) would modify their input
argument by injecting an "_id" key containing the generated ObjectId (i.e.
[MongoId][mongoid] object). This behavior was a bit of a hack, as it did not
rely on the argument being [passed by reference][byref]; it directly modified
memory through the extension API and could not be implemented in PHP userland.
As such, it is no longer done in the new driver and library.
[insert]: http://php.net/manual/en/mongocollection.insert.php
[batchinsert]: http://php.net/manual/en/mongocollection.batchinsert.php
[mongoid]: http://php.net/manual/en/class.mongoid.php
[byref]: http://php.net/manual/en/language.references.pass.php
IDs of inserted documents (whether generated or not) may be accessed through the
result objects returned by the write methods:
* MongoDB\InsertOneResult::getInsertedId() for [insertOne()][insertone]
* MongoDB\InsertManyResult::getInsertedIds() for [insertMany()][insertmany]
* MongoDB\BulkWriteResult::getInsertedIds() for [bulkWrite()][bulkwrite]
[insertmany]: classes/collection.md#insertmany
[bulkwrite]: classes/collection.md#bulkwrite
### MongoWriteBatch
The legacy driver's [MongoWriteBatch][batch] classes have been replaced with a
general-purpose [bulkWrite()][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
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