Commit 38e57b6e authored by Jeremy Mikola's avatar Jeremy Mikola

Merge pull request #227

parents dd7058c9 20f4fc4f
# 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
arg_name: param
name: $uri
type: string
description: |
The URI of the standalone, replica set, or sharded cluster to which to connect. Refer
to the :manual:`MongoDB connection string reference </reference/connection-string>`
for formatting.
Defaults to ``mongodb://localhost:27017`` if unspecified.
interface: phpmethod
operation: MongoDB\\Client::__construct
optional: true
position: 1
---
arg_name: param
name: $uriOptions
type: array
description: |
Specifies additional URI options, such as authentication credentials
or query string parameters. The options specified in ``$uriOptions``
take precedence over any analogous options present in the
``$uri`` string.
post: |
Refer to the :php:`MongoDB\\Driver\\Manager::__construct()
<mongodb-driver-manager.construct>` extension reference and
:manual:`MongoDB connection string </reference/connection-string>`
documentation for valid options.
interface: phpmethod
operation: MongoDB\\Client::__construct
optional: true
position: 2
---
arg_name: param
name: $driverOptions
type: array
description: |
Specify driver-specific options. In addition to any
options supported by the :php:`extension <mongodb-driver-manager>`,
the |php-library| allows you to specify a default ``typeMap`` to
apply to the cursors it creates. Refer to the driver's
:php:`Persistence documentation <mongodb-persistence>` for more
about type maps.
interface: phpmethod
operation: MongoDB\\Client::__construct
optional: true
position: 3
...
\ No newline at end of file
arg_name: option
interface: phpmethod
operation: MongoDB\\Client::dropDatabase
source:
file: apiargs-common-option.yaml
ref: typeMap
position: 1
...
source:
ref: $databaseName
file: apiargs-common-param.yaml
arg_name: param
interface: phpmethod
operation: MongoDB\\Client::dropDatabase
---
source:
ref: $options
file: apiargs-common-param.yaml
arg_name: param
interface: phpmethod
operation: MongoDB\\Client::dropDatabase
position: 2
...
source:
ref: $databaseName
file: apiargs-common-param.yaml
arg_name: param
interface: phpmethod
operation: MongoDB\\Client::__get
...
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
position: 1
...
source:
ref: $options
file: apiargs-common-param.yaml
arg_name: param
interface: phpmethod
operation: MongoDB\\Client::listDatabases
position: 1
...
source:
ref: readConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Client::selectDatabase
replacement:
resource: "database"
---
source:
ref: readPreference
file: apiargs-common-option.yaml
operation: MongoDB\\Client::selectDatabase
replacement:
resource: "database"
---
source:
ref: typeMap
file: apiargs-common-option.yaml
operation: MongoDB\\Client::selectDatabase
---
source:
ref: writeConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Client::selectDatabase
replacement:
resource: "database"
...
\ No newline at end of file
source:
ref: $databaseName
file: apiargs-common-param.yaml
operation: MongoDB\\Client::selectDatabase
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Client::selectDatabase
position: 2
...
arg_name: option
name: allowDiskUse
type: boolean
description: |
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``.
interface: phpmethod
operation: MongoDB\\Collection::aggregate
optional: true
position: 1
---
arg_name: option
name: batchSize
type: integer
description: |
The number of documents to return per batch
interface: phpmethod
operation: MongoDB\\Collection::aggregate
optional: true
position: 2
---
source:
ref: bypassDocumentValidation
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::aggregate
position: 5
---
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::aggregate
position: 4
---
source:
ref: readConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::selectDatabase
replacement:
resource: "aggregation"
position: 5
---
source:
ref: readPreference
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::selectDatabase
replacement:
resource: "aggregation"
position: 6
---
source:
ref: typeMap
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::selectDatabase
position: 7
---
arg_name: param
name: useCursor
type: boolean
description: |
Indicates whether the command will request that the server provide
results using a cursor. The default is ``true``.
For MongoDB version 2.6 or later, ``useCursor`` allows users to turn
off cursors if necessary to aid in mongod/mongos upgrades.
``useCursor`` is ignored for MongoDB versions prior to 2.6 as
aggregation cursors are not available pre-2.6.
interface: phpmethod
operation: MongoDB\\Collection::aggregate
optional: true
position: 8
...
arg_name: param
name: $pipeline
type: array
description: |
Specifies an :manual:`aggregation pipeline </core/aggregation-pipeline>` operation.
interface: phpmethod
operation: MongoDB\\Collection::aggregate
optional: true
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::aggregate
position: 2
...
\ No newline at end of file
source:
ref: bypassDocumentValidation
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::bulkWrite
position: 1
---
arg_name: option
name: ordered
type: boolean
description: |
If ``true``: when an insert fails, the operation returns without performing the
remaining writes.
If ``false``: when a write fails, the operation will continue with the
remaining writes, if any.
The default is ``true``.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::bulkWrite
position: 2
---
source:
ref: writeConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::bulkWrite
replacement:
resource: "write"
position: 3
...
arg_name: param
name: $operations
type: array
description: |
An array containing the write operations to perform. {{role}}
supports :phpmethod:`deleteMany <MongoDB\\Collection::deleteMany>`,
:phpmethod:`deleteOne <MongoDB\\Collection::deleteOne>`, :phpmethod:`insertOne
<MongoDB\\Collection::insertOne>`, :phpmethod:`replaceOne
<MongoDB\\Collection::replaceOne>`, :phpmethod:`updateMany
<MongoDB\\Collection::updateMany>`, and :phpmethod:`updateOne
<MongoDB\\Collection::updateOne>` operations in the following array
structure:
.. code-block:: php
[
[ 'deleteMany' => [ $filter ] ],
[ 'deleteOne' => [ $filter ] ],
[ 'insertOne' => [ $document ] ],
[ 'replaceOne' => [ $filter, $replacement, $options ] ],
[ 'updateMany' => [ $filter, $update, $options ] ],
[ 'updateOne' => [ $filter, $update, $options ] ],
]
post: |
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.
interface: phpmethod
operation: MongoDB\\Collection::bulkWrite
optional: true
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::bulkWrite
interface: phpmethod
position: 2
...
\ No newline at end of file
arg_name: param
name: $manager
type: :php:`MongoDB\\Driver\\Manager <class.mongodb-driver-manager>`
description: |
The :php:`Manager <mongodb-driver-manager>` instance from the driver.
The manager maintains connections between the driver and your MongoDB
instances.
interface: phpmethod
operation: MongoDB\\Collection::__construct
optional: false
position: 1
---
source:
ref: $databaseName
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::__construct
replacement:
select: ""
position: 2
---
source:
ref: $collectionName
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::__construct
replacement:
select: ""
position: 3
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::__construct
position: 4
...
\ No newline at end of file
arg_name: option
name: hint
type: string or array|object
description: |
The index to use. If you specify a document, it is interpreted as
an index specification and a name will be generated.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::count
position: 1
---
arg_name: option
name: limit
type: integer
description: |
The maximum number of documents to return.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::count
position: 2
---
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::count
position: 3
---
source:
ref: readConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::count
replacement:
resource: "count"
position: 4
---
source:
ref: readPreference
file: apiargs-common-option.yaml
replacement:
resource: "count"
position: 5
---
arg_name: option
name: skip
type: integer
description: |
The number of documents to skip before returning the documents.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::count
position: 6
...
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::count
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::count
position: 2
...
arg_name: option
name: unique
type: boolean
description: |
Creates a :manual:`unique </core/index-unique>` index.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 1
---
arg_name: option
name: partialFilterExpression
type: array|object
description: |
Creates a :manual:`partial </core/index-partial>` index.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 2
---
arg_name: option
name: sparse
type: boolean
description: |
Creates a :manual:`sparse </core/index-sparse>` index.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 3
---
arg_name: option
name: expireAfterSeconds
type: integer
description: |
Creates a :manual:`TTL </core/index-ttl>` index.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 4
---
arg_name: option
name: name
type: string
description: |
Specifies the name for the index. By default, MongoDB creates index
names based on the key.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 5
---
arg_name: option
name: background
type: string
description: |
Instructs MongoDB to build the index :manual:`as a background
</core/index-creation>` process.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 6
---
arg_name: option
name: 2dsphereIndexVersion
type: integer
description: |
Specifies the :manual:`version of a 2dsphere </core/2dsphere>` index
to create.
MongoDB 2.6 introduced version 2 of 2dsphere indexes. Version 2 is
the default version of 2dsphere indexes created in MongoDB 2.6 and
later series. ``2dsphereIndexVersion`` enables you to overrride the
default version 2.
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 7
---
arg_name: option
name: socketTimeoutMS
type: integer
description: |
Specifies the time limit, in milliseconds, for socket
communication. If the :program:`mongod` does not respond within the
timeout period, a ``MongoCursorTimeoutException`` is thrown and
there will be no way to determine if the server actually handled the
write or not. Specify ``-1`` to block indefinitely. The default value
is 30000 (30 seconds).
interface: phpmethod
operation: MongoDB\\Collection::createIndex
optional: true
position: 8
---
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::createIndex
position: 9
...
arg_name: param
name: $key
type: array|object
description: |
Specifies the field or fields to index and the index order.
For example, the following specifies a descending index
on the ``username`` field:
.. code-block:: php
$key = [ 'username' => -1 ];
operation: MongoDB\\Collection::createIndex
interface: phpmethod
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Collection::createIndex
position: 2
...
\ No newline at end of file
source:
ref: writeConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::deleteMany
replacement:
resource: "delete"
position: 1
...
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::deleteMany
replacement:
verb: "delete"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::deleteMany
position: 2
...
source:
ref: writeConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::deleteOne
replacement:
resource: "delete"
position: 1
...
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::deleteOne
replacement:
verb: "delete"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::deleteOne
position: 2
...
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::distinct
position: 1
---
source:
ref: readConcern
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::distinct
replacement:
resource: "distinct"
position: 2
---
source:
ref: readPreference
file: apiargs-common-option.yaml
replacement:
resource: "distinct"
position: 3
...
arg_name: param
name: $fieldName
type: string
description: |
The field for which to return distinct values.
interface: phpmethod
operation: MongoDB\\Collection::distinct
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $filter
position: 2
optional: true
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::count
position: 3
...
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::drop
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $options
interface: phpmethod
operation: MongoDB\\Collection::drop
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::dropIndex
position: 1
...
\ No newline at end of file
arg_name: param
name: $indexName
type: string
description: |
The name of the index to drop. View the existing indexes on the
collection using the :phpmethod:`listIndexes
<MongoDB\\Collection::listIndexes>` method.
interface: phpmethod
operation: MongoDB\\Collection::dropIndex
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
interface: phpmethod
operation: MongoDB\\Collection::dropIndex
position: 2
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::dropIndexes
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Collection::dropIndexes
position: 1
...
\ No newline at end of file
name: sort
type: array|object
optional: true
description: |
The sort specification for the ordering of the results.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 2
---
name: projection
type: array|object
optional: true
description: |
The :ref:`projection specification <projections>` to determine
which fields to include in the returned documents. See
:manual:`Project Fields to Return from Query
</tutorial/project-fields-from-query-results>` in the MongoDB
manual.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 1
---
name: skip
type: integer
optional: true
description: |
Number of documents to skip. Defaults to 0.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 3
---
name: limit
type: integer
optional: true
description: |
The maximum number of documents to return. If unspecified,
then defaults to no limit. A limit of 0 is equivalent to setting no
limit.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 4
---
name: batchSize
type: integer
optional: true
description: |
The number of documents to return in the first batch.
Defaults to 101. A batchSize of 0 means that the cursor will be
established, but no documents will be returned in the first batch.
Unlike the previous wire protocol version, a batchSize of 1 for
the :dbcommand:`find` command does not close the cursor.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 5
---
name: comment
type: string
optional: true
description: |
A comment to attach to the query to help interpret and trace query
:dbcommand:`profile` data.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 6
---
arg_name: option
name: cursorType
type: integer
description: |
Indicates the type of cursor to use. The cursor types are
``MongoDB\Operation\Find`` class constants.
Must be either
``NON_TAILABLE``, ``TAILABLE``, or ``TAILABLE_AWAIT``. The default is
``NON_TAILABLE``.
interface: phpmethod
operation: MongoDB\\Collection::find
optional: true
position: 7
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Collection::find
position: 8
---
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Collection::find
position: 9
---
source:
file: apiargs-common-option.yaml
ref: readPreference
pre: |
For use with MongoDB 3.0 and earlier.
operation: MongoDB\\Collection::find
position: 10
---
name: oplogReplay
type: boolean
optional: true
description: |
Internal use for replica sets. To use oplogReplay, you must include
the following condition in the filter:
.. code-block:: javascript
{ ts: { $gte: <timestamp> } }
The :php:`MongoDB\\BSON\\Timestamp <class.mongodb-bson-timestamp>`
class reference describes how to represent MongoDB's BSON
timestamp type with PHP.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 11
---
name: noCursorTimeout
type: boolean
optional: true
description: |
Prevents the server from timing out idle cursors after an inactivity
period (10 minutes).
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 12
---
name: allowPartialResults
type: boolean
optional: true
description: |
For queries against a sharded collection, returns partial results from
the :program:`mongos` if some shards are unavailable instead of
throwing an error.
arg_name: field
operation: MongoDB\\Collection::find
interface: phpmethod
position: 13
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::find
position: 14
---
arg_name: option
name: modifiers
type: array
description: |
Meta-operators that modify the output or behavior of a query.
:manual:`Cursor Methods </reference/method/js-cursor`> describes the
query modification methods available in MongoDB.
interface: phpmethod
operation: MongoDB\\Collection::find
optional: true
position: 15
...
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::find
replacement:
verb: "query"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::find
position: 2
...
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: projection
operation: MongoDB\\Collection::findOne
position: 1
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: sort
operation: MongoDB\\Collection::findOne
position: 2
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: skip
operation: MongoDB\\Collection::findOne
position: 3
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: comment
operation: MongoDB\\Collection::findOne
position: 4
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: modifiers
operation: MongoDB\\Collection::findOne
position: 5
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Collection::findOne
position: 6
---
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Collection::findOne
position: 7
---
source:
file: apiargs-common-option.yaml
ref: readPreference
pre: |
For use with MongoDB 3.0 and earlier.
operation: MongoDB\\Collection::findOne
position: 8
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::findOne
position: 9
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOne
replacement:
verb: "query"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOne
position: 2
...
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: projection
operation: MongoDB\\Collection::findOneAndDelete
position: 1
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: sort
operation: MongoDB\\Collection::findOneAndDelete
position: 2
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Collection::findOneAndDelete
position: 3
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::findOneAndDelete
position: 4
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndDelete
replacement:
verb: "query"
position: 1
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndDelete
position: 2
...
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: projection
operation: MongoDB\\Collection::findOneAndReplace
position: 1
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: sort
operation: MongoDB\\Collection::findOneAndReplace
position: 2
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Collection::findOneAndReplace
position: 3
---
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::findOneAndReplace
position: 4
---
source:
file: apiargs-MongoDBCollection-method-findOneAndUpdate-option.yaml
ref: returnDocument
operation: MongoDB\\Collection::findOneAndReplace
position: 5
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::findOneAndReplace
position: 6
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::findOneAndReplace
position: 7
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndReplace
replacement:
verb: "query"
optional: false
position: 1
---
arg_name: param
name: $replacement
type: array|object
description: |
The document to replace.
interface: phpmethod
operation: MongoDB\\Collection::findOneAndReplace
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndReplace
position: 3
...
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: projection
operation: MongoDB\Collection::findOneAndUpdate
position: 1
---
source:
file: apiargs-MongoDBCollection-method-find-option.yaml
ref: sort
operation: MongoDB\Collection::findOneAndUpdate
position: 2
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\Collection::findOneAndUpdate
position: 3
---
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\Collection::findOneAndUpdate
position: 4
---
arg_name: option
name: returnDocument
type: integer
description: |
Specifies whether to return the document before the {{event}}, or
after. ``returnDocument`` supports the following values:
- ``MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE`` (*default*)
- ``MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER``
optional: true
replacement:
event: "update is applied"
interface: phpmethod
operation: MongoDB\Collection::findOneAndUpdate
position: 5
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::findOneAndUpdate
position: 6
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\Collection::findOneAndUpdate
position: 7
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndUpdate
replacement:
verb: "query"
optional: false
position: 1
---
arg_name: param
name: $update
type: array|object
description: |
Specifies the field and value combinations to update and any
relevant update operators. ``$update`` uses MongoDB's
:method:`update operators </reference/operator/update>`.
interface: phpmethod
operation: MongoDB\\Collection::findOneAndUpdate
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::findOneAndUpdate
position: 3
...
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::insertMany
position: 1
---
source:
file: apiargs-MongoDBCollection-method-bulkWrite-option.yaml
ref: ordered
operation: MongoDB\\Collection::insertMany
position: 2
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::insertMany
position: 3
...
\ No newline at end of file
arg_name: param
name: $documents
type: array
description: |
The documents to insert into the collection.
interface: phpmethod
operation: MongoDB\\Collection::insertMany
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Collection::insertMany
position: 2
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::insertOne
position: 1
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::insertOne
position: 2
...
\ No newline at end of file
arg_name: param
name: $document
type: array|object
description: |
The document to insert into the collection.
interface: phpmethod
operation: MongoDB\\Collection::insertOne
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Collection::insertOne
position: 2
...
\ No newline at end of file
source:
ref: maxTimeMS
file: apiargs-common-option.yaml
operation: MongoDB\\Collection::listIndexes
position: 1
...
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::listIndexes
position: 1
...
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::replaceOne
position: 1
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::replaceOne
position: 2
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::replaceOne
position: 3
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::replaceOne
replacement:
verb: "query"
optional: false
position: 1
---
arg_name: param
name: $replacement
type: array
description: |
The document to replace.
interface: phpmethod
operation: MongoDB\\Collection::replaceOne
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::replaceOne
position: 3
...
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::updateMany
position: 1
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::updateMany
position: 2
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::updateMany
position: 3
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::updateMany
replacement:
verb: "query"
optional: false
position: 1
---
source:
file: apiargs-MongoDBCollection-method-findOneAndUpdate-param.yaml
ref: $update
operation: MongoDB\\Collection::updateMany
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::updateMany
position: 3
...
source:
file: apiargs-common-option.yaml
ref: bypassDocumentValidation
operation: MongoDB\\Collection::updateOne
position: 1
---
source:
file: apiargs-common-option.yaml
ref: upsert
operation: MongoDB\\Collection::updateOne
position: 2
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::updateOne
position: 3
...
\ No newline at end of file
source:
ref: $filter
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::updateOne
replacement:
verb: "query"
optional: false
position: 1
---
source:
file: apiargs-MongoDBCollection-method-findOneAndUpdate-param.yaml
ref: $update
operation: MongoDB\\Collection::updateOne
optional: false
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::updateOne
position: 3
...
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Collection::withOptions
description: |
The default read concern to use for collection operations. Defaults
to the original Collection's specified read concern.
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Collection::withOptions
description: |
The default read preference to use for collection operations.
Defaults to the original Collection's read preference.
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Collection::withOptions
description: |
Default type map for cursors and BSON documents. Defaults to the
original Collection's type map value.
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Collection::withOptions
description: |
The default write concern to use for collection operations. Defaults
to the original Collection's specified write concern.
...
\ No newline at end of file
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Collection::withOptions
position: 1
...
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::command
position: 1
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::command
position: 2
...
arg_name: param
name: $command
type: string
description: |
The name of the :manual:`database command </reference/command>`
to execute.
interface: phpmethod
operation: MongoDB\\Database::command
optional: false
position: 1
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::command
position: 2
...
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Database::__construct
position: 1
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::__construct
position: 2
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::__construct
position: 3
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Database::__construct
position: 4
...
\ No newline at end of file
source:
file: apiargs-MongoDBCollection-method-construct-param.yaml
ref: $manager
operation: MongoDB\\Database::__construct
position: 1
---
source:
ref: $databaseName
file: apiargs-common-param.yaml
operation: MongoDB\\Database::__construct
position: 2
---
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Database::__construct
position: 2
...
\ No newline at end of file
arg_name: option
name: autoIndexId
type: boolean
description: |
*Default: true*. Specify false to disable the automatic creation of
an index on the _id field.
.. important::
For replica sets, do not set ``autoIndexId`` to ``false``.
.. deprecated:: 3.2. The ``autoIndexId`` option will be removed in MongoDB v3.4.
optional: true
interface: phpmethod
operation: MongoDB\\Database::createCollection
position: 1
---
arg_name: option
name: indexOptionDefaults
type: array
description: |
Allows users to specify a default configuration for indexes when
creating a collection.
The ``indexOptionDefaults`` option accepts a ``storageEngine`` document,
which should take the following form::
{ <storage-engine-name>: <options> }
Storage engine configurations specified when creating indexes are
validated and logged to the :term:`oplog` during replication to support
replica sets with members that use different storage engines.
optional: true
interface: phpmethod
operation: MongoDB\\Database::createCollection
position: 2
---
arg_name: option
name: capped
type: boolean
description: |
To create a capped collection, specify ``true``. If you specify
``true``, you must also set a maximum size in the ``size`` option.
optional: true
interface: phpmethod
operation: MongoDB\\Database::createCollection
position: 3
---
arg_name: option
name: size
type: integer
description: |
Specify a maximum size in bytes for a capped collection. Once a
capped collection reaches its maximum size, MongoDB removes the older
documents to make space for the new documents. The ``size`` option is
required for capped collections and ignored for other collections.
optional: true
interface: phpmethod
operation: MongoDB\\Database::createCollection
position: 4
---
arg_name: option
name: max
type: integer
description: |
The maximum number of documents allowed in the capped collection. The
``size`` option takes precedence over this limit. If a capped
collection reaches the ``size`` limit before it reaches the maximum
number of documents, MongoDB removes old documents. If you prefer to
use the ``max`` limit, ensure that the ``size`` limit, which is
required for a capped collection, is sufficient to contain the
maximum number of documents.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 5
---
arg_name: option
name: storageEngine
type: array
description: |
Available for the WiredTiger storage engine only.
Allows users to specify configuration to the storage engine on a
per-collection basis when creating a collection. The value of the
``storageEngine`` option should take the following form::
{ <storage-engine-name>: <options> }
Storage engine configurations specified when creating collections are
validated and logged to the :term:`oplog` during replication to support
replica sets with members that use different storage engines.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 6
---
arg_name: option
name: flags
type: integer
description: |
Available for the MMAPv1 storage engine only to set the
``usePowerOf2Sizes`` and ``noPadding`` flags.
The |php-library| provides constants that you can combine with a
:php:`bitwise OR operator <language.operators.bitwise>` to set the
flag values:
- ``MongoDB\Operation\CreateCollection::USE_POWER_OF_2_SIZES``: ``1``
- ``MongoDB\Operation\CreateCollection::NO_PADDING``: ``2``
Defaults to ``1``.
.. note::
MongoDB 3.0 and later ignores the ``usePowerOf2Sizes`` flag. See
:manual:`collMod </reference/command/collMod>` and
:manual:`db.createCollection()
</reference/method/db.createCollection>` for more information.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 7
---
arg_name: option
name: validator
type: array
description: |
Allows users to specify :manual:`validation rules or expressions
</core/document-validation>` for the collection. For more information,
see :manual:`Document Validation </core/document-validation>`
in the MongoDB manual.
The ``validator`` option takes an array that specifies the
validation rules or expressions. You can specify the expressions using
the same operators as MongoDB's :manual:`query operators </reference/operator/query>`
with the exception of :query:`$geoNear`, :query:`$near`,
:query:`$nearSphere`, :query:`$text`, and :query:`$where`.
.. note::
- Validation occurs during updates and inserts. Existing
documents do not undergo validation checks until modification.
- You cannot specify a validator for collections in the ``admin``,
``local``, and ``config`` databases.
- You cannot specify a validator for ``system.*`` collections.
operation: MongoDB\\Database::createCollection
interface: phpmethod
optional: true
position: 8
---
arg_name: option
name: validationLevel
type: string
description: |
Determines how strictly MongoDB applies the
validation rules to existing documents during an update.
.. list-table::
:header-rows: 1
* - ``validationLevel``
- Description
* - ``"off"``
- No validation for inserts or updates.
* - ``"strict"``
- **Default** Apply validation rules to all inserts and all
updates.
* - ``"moderate"``
- Apply validation rules to inserts and to updates on existing *valid*
documents. Do not apply rules to updates on existing *invalid*
documents.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 9
---
arg_name: option
name: validationAction
type: string
description: |
Determines whether to ``error`` on invalid documents or just ``warn``
about the violations but allow invalid documents to be inserted.
.. important::
Validation of documents only applies to those documents as
determined by the ``validationLevel``.
.. list-table::
:header-rows: 1
* - ``validationAction``
- Description
* - ``"error"``
- **Default** Documents must pass validation before the write occurs.
Otherwise, the write operation fails.
* - ``"warn"``
- Documents do not have to pass validation. If the document fails
validation, the write operation logs the validation failure.
interface: phpmethod
operation: MongoDB\\Database::createCollection
optional: true
position: 10
---
source:
file: apiargs-common-option.yaml
ref: maxTimeMS
operation: MongoDB\\Database::createCollection
position: 11
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::createCollection
position: 12
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::createCollection
position: 1
optional: false
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::createCollection
position: 2
optional: true
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::dropCollection
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::dropCollection
position: 1
optional: false
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::dropCollection
position: 2
optional: true
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::dropCollection
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::dropCollection
position: 1
optional: false
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::dropCollection
position: 2
optional: true
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::__get
position: 1
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Database::listCollections
position: 1
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::listCollections
position: 2
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::listCollections
position: 3
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Database::listCollections
position: 4
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::listCollections
position: 1
optional: true
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Database::selectCollection
position: 1
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::selectCollection
position: 2
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::selectCollection
position: 3
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Database::selectCollection
position: 4
...
\ No newline at end of file
source:
file: apiargs-common-param.yaml
ref: $collectionName
operation: MongoDB\\Database::selectCollection
position: 1
optional: false
---
source:
file: apiargs-common-param.yaml
ref: $options
operation: MongoDB\\Database::selectCollection
position: 2
...
\ No newline at end of file
source:
file: apiargs-common-option.yaml
ref: readConcern
operation: MongoDB\\Database::withOptions
description: |
The default read concern to use for database operations. Defaults
to the original Databases's specified read concern.
---
source:
file: apiargs-common-option.yaml
ref: readPreference
operation: MongoDB\\Database::withOptions
description: |
The default read preference to use for database operations.
Defaults to the original Database's read preference.
---
source:
file: apiargs-common-option.yaml
ref: typeMap
operation: MongoDB\\Database::withOptions
description: |
Default type map for cursors and BSON documents. Defaults to the
original Database's type map value.
---
source:
file: apiargs-common-option.yaml
ref: writeConcern
operation: MongoDB\\Database::withOptions
description: |
The default write concern to use for database operations. Defaults
to the original Database's specified write concern.
...
\ No newline at end of file
source:
ref: $options
file: apiargs-common-param.yaml
operation: MongoDB\\Database::withOptions
position: 1
...
arg_name: option
name: readConcern
type: :php:`MongoDB\\Driver\\ReadConcern <class.mongodb-driver-readconcern>`
description: |
The default read concern to use for {{resource}} operations. Defaults
to the Client's specified read concern.
interface: phpmethod
operation: selectCollection
optional: true
position: 1
replacement:
resource: "collection"
---
arg_name: option
description: |
The default read preference to use for {{resource}} operations.
Defaults to the {{parent}}'s read preference.
interface: phpmethod
name: readPreference
operation: selectCollection
optional: true
position: 2
type: :php:`MongoDB\\Driver\\ReadPreference <class.mongodb-driver-readpreference>`
replacement:
resource: "collection"
parent: "Client"
---
arg_name: option
description: |
Default type map for cursors and BSON documents. Defaults to the
{{parent}}'s type map.
interface: phpmethod
name: typeMap
operation: selectCollection
optional: true
position: 3
type: array
replacement:
parent: "Client"
---
arg_name: option
name: writeConcern
type: :php:`MongoDB\\Driver\\WriteConcern <class.mongodb-driver-writeconcern>`
description: |
The default write concern to use for {{resource}} operations. Defaults
to the {{parent}}'s specified write concern.
interface: phpmethod
operation: selectCollection
optional: true
position: 4
replacement:
resource: "collection"
parent: "Client"
---
arg_name: option
name: maxTimeMS
description: |
The cumulative time limit in milliseconds for processing operations on
the cursor. MongoDB aborts the operation at the earliest following
:term:`interrupt point`.
interface: phpmethod
operation: listDatabases
type: integer
optional: true
position: 5
---
arg_name: option
name: bypassDocumentValidation
type: boolean
description: |
If ``true``, allows the write operation to circumvent document level
validation. This only applies when using the :pipeline:`$out` stage.
Document validation requires MongoDB v3.2 or later: if you are using
an earlier version of MongoDB, this option will be ignored.
interface: phpmethod
operation: aggregate
optional: true
position: 6
---
arg_name: option
name: upsert
type: boolean
description: |
When true, {{role}} creates a new document if no document
matches the query. If a document matches the query, {{role}}
performs an update. To avoid multiple upserts, ensure that the query
fields are uniquely indexed.
The default is ``false``.
optional: true
interface: phpmethod
operation: MongoDB\\Collection::findOneAndUpdate
position: 7
...
\ No newline at end of file
arg_name: param
name: $databaseName
type: string
description: |
The name of the database{{select}}.
interface: phpmethod
operation: selectCollection
optional: false
replacement:
select: " to select"
position: 1
---
arg_name: param
name: $collectionName
type: string
description: |
The name of the collection{{select}}.
interface: phpmethod
operation: selectCollection
optional: false
replacement:
select: " to select"
position: 2
---
arg_name: param
name: $options
type: array
description: |
An array specifying the desired options.
interface: phpmethod
operation: selectCollection
optional: true
position: 3
---
arg_name: param
name: $filter
type: array|object
description: |
The filter criteria that specifies the documents to {{verb}}.
interface: phpmethod
operation: count
optional: false
position: 4
replacement:
verb: "count"
...
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('users','restaurants');
$newUser = $collection->insertOne(
[
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Anna Bennett'
],
);
echo "<pre>";
var_dump($newUser);
The output would resemble:
.. code-block:: none
object(MongoDB\InsertOneResult)#13 (3) {
["writeResult":"MongoDB\InsertOneResult":private]=>
object(MongoDB\Driver\WriteResult)#12 (9) {
["nInserted"]=>
int(1)
["nMatched"]=>
int(0)
["nModified"]=>
int(0)
["nRemoved"]=>
int(0)
["nUpserted"]=>
int(0)
["upsertedIds"]=>
array(0) {
}
["writeErrors"]=>
array(0) {
}
["writeConcernError"]=>
NULL
["writeConcern"]=>
array(4) {
["w"]=>
NULL
["wmajority"]=>
bool(false)
["wtimeout"]=>
int(0)
["journal"]=>
NULL
}
}
["insertedId":"MongoDB\InsertOneResult":private]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "577282631f417d1823121691"
}
["isAcknowledged":"MongoDB\InsertOneResult":private]=>
bool(true)
}
\ No newline at end of file
ref: _bson-deserialization
content: |
.. note::
{{method}} does not
yet support a ``typeMap`` option for BSON deserialization of the
returned document.
Classes implementing
:php:`MongoDB\\BSON\\Persistable <class.mongodb-bson-persistable>`
are deserialized according to the :php:`persistance
<mongodb.persistance>` specification.
...
\ No newline at end of file
ref: bson-deserialization-findOneAndDelete
source:
file: extracts-bson-deserialization-base.yaml
ref: _bson-deserialization
replacement:
method: ":phpmethod:`MongoDB\\Collection::findOneAndDelete`"
---
ref: bson-deserialization-findOneAndReplace
source:
file: extracts-bson-deserialization-base.yaml
ref: _bson-deserialization
replacement:
method: ":phpmethod:`MongoDB\\Collection::findOneAndReplace`"
---
ref: bson-deserialization-findOneAndUpdate
source:
file: extracts-bson-deserialization-base.yaml
ref: _bson-deserialization
replacement:
method: ":phpmethod:`MongoDB\\Collection::findOneAndUpdate`"
...
# 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/)
===================
MongoDB PHP Library
===================
.. default-domain:: mongodb
The |php-library| provides a high-level abstraction
around the lower-level `PHP Driver <https://php.net/mongodb>`_, also
known as the ``mongodb`` extension.
While the ``mongodb`` extension provides a limited API for executing
commands, queries, and write operations, the |php-library|
implements an API similar to that of the `legacy PHP driver
<http://php.net/manual/en/book.mongo.php>`_. The library contains
abstractions for client, database, and collection objects, and provides
methods for CRUD operations and common commands such as index and
collection management.
If you are developing a PHP application with MongoDB, you should consider
using this library, or another high-level abstraction, instead of the
extension alone.
For additional information about the MongoDB PHP Library and the
``mongodb`` extension, see the `Architecture Overview
<http://php.net/manual/en/mongodb.overview.php>`_ article in the
extension 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 <https://derickrethans.nl/new-drivers.html>`_
- `Part Two: Architecture
<https://derickrethans.nl/new-drivers-part2.html>`_
- `Part Three: Cursor Behaviour
<https://derickrethans.nl/new-drivers-part3-cursor.html>`_
API Reference
-------------
Generated API reference documentation for the library is available at:
`http://mongodb.github.io/mongo-php-library/api
<http://mongodb.github.io/mongo-php-library/api>`_
New to MongoDB?
---------------
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/>`_
.. class:: hidden
.. toctree::
:titlesonly:
Installation </tutorial/install-php-library>
/tutorial
/upgrade
/reference
.. /getting-started
\ No newline at end of file
=========
Reference
=========
.. default-domain:: mongodb
.. toctree::
:titlesonly:
/reference/bson
/reference/class/MongoDBClient
/reference/class/MongoDBDatabase
/reference/class/MongoDBCollection
====
BSON
====
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Overview
--------
MongoDB stores data records as BSON documents. BSON is a binary
representation of :term:`JSON` documents, though it contains more data
types than JSON. For the BSON spec, see `bsonspec.org <http://bsonspec.org/>`_.
By default, the |php-library| returns BSON documents as
``MongoDB\Model\BSONDocument`` objects and BSON arrays as
``MongoDB\Model\BSONArray`` objects. ``MongoDB\Model\BSONDocument`` and
``MongoDB\Model\BSONArray`` extend PHP's
:php:`ArrayObject <arrayobject>` class and implement the MongoDB PHP
driver's :php:`MongoDB\\BSON\\Serializable <mongodb-bson-serializable>`
and :php:`MongoDB\\BSON\\Unserializable <mongodb-bson-unserializable>`
interfaces.
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 :phpclass:`MongoDB\\Client`, :phpclass:`MongoDB\\Database`, and
:phpclass:`MongoDB\\Collection` classes accept a ``typeMap`` option,
which applies to any supporting methods and selected classes by default.
The :phpclass:`MongoDB\\Client`, :phpclass:`MongoDB\\Database`, and
:phpclass:`MongoDB\\Collection` classes use the following type map by
default:
.. code-block:: php
[
'array' => 'MongoDB\Model\BSONArray',
'document' => 'MongoDB\Model\BSONDocument',
'root' => 'MongoDB\Model\BSONDocument',
]
Serialization and deserialization of PHP variables into MongoDB
---------------------------------------------------------------
``Persistable`` Classes
~~~~~~~~~~~~~~~~~~~~~~~
The PHP driver's :php:`persistence <mongodb.persistence>` specification
specifies how classes implementing :php:`MongoDB\\BSON\\Persistable
<mongodb-bson-persistable>` are serialized and deserialized, and is
analogous to PHP's :php:`Serializable interface <class.serializable>`.
The PHP :php:`driver <mongodb>` automatically handles serialization and
deserialization for classes implementing ``MongoDB\BSON\Persistable``
without requiring the use of the ``typeMap`` option.
Consider the following class definition:
.. code-block:: php
<?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 constructs a ``Person`` object, inserts it into the
database, and reads it back as an object of the same type:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->persons;
$result = $collection->insertOne(new Person('Bob'));
$person = $collection->findOne(['_id' => $result->getInsertedId()]);
var_dump($person);
The output would then resemble:
.. code-block:: none
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:
.. code-block:: js
{
"_id" : ObjectId("56fad2c36118fd2e9820cfc1"),
"__pclass" : BinData(128,"UGVyc29u"),
"name" : "Bob",
"createdAt" : ISODate("2016-03-29T19:08:51.218Z")
}
.. note::
:php:`MongoDB\\BSON\\Persistable <mongodb-bson-persistable>` may only be used
for root and embedded BSON documents. BSON arrays are not supported.
Emulating the Legacy Driver
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The legacy :php:`mongo extension <mongo>` returned both BSON
documents and arrays as PHP arrays. While PHP arrays are convenient to
work with, this behavior was problematic:
- 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
caused by unsetting a key to remove an element and
forgetting to reindex the array.
The |php-library|'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, you can use the ``typeMap`` option to have
the library return everything as a PHP array:
.. code-block:: php
<?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:
.. code-block:: php
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"
}
=====================
MongoDB\\Client Class
=====================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpclass:: MongoDB\\Client
Serves as an entry point for the |php-library|. ``MongoDB\Client``
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. ``MongoDB\Client`` is analogous to the
driver's :php:`MongoDB\\Driver\\Manager <mongodb-driver-manager>`
class, which it composes.
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBClient__construct
/reference/method/MongoDBClient__get
/reference/method/MongoDBClient-dropDatabase
/reference/method/MongoDBClient-listDatabases
/reference/method/MongoDBClient-selectCollection
/reference/method/MongoDBClient-selectDatabase
=========================
MongoDB\\Collection Class
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpclass:: MongoDB\\Collection
Provides methods for common operations on collections and documents,
including CRUD operations and index management.
You can construct collections directly using the PHP extension's
``Manager`` class, select a collection from the |php-library|'s
:phpclass:`MongoDB\\Client` or :phpclass:`MongoDB\\Database`
classes, or create a collection from an existing collection using the
:phpmethod:`withOptions <MongoDB\\Collection::withOptions>` clone method.
:phpclass:`MongoDB\\Collection` supports the :php:`readConcern
<mongodb-driver-readconcern>`, :php:`readPreference
<mongodb-driver-readpreference>`, :php:`typeMap
<mongodb.persistence.php#mongodb.persistence.typemaps>`, and
:php:`writeConcern <mongodb-driver-writeconcern>` options.
If you omit an option, the collection inherits the value from the
Manager constructor argument or the Database object used to select
the collection.
Operations within the ``Collection`` class
inherit the Collection's options.
The :phpmethod:`MongoDB\\Collection::aggregate` method (when not
using a cursor), :phpmethod:`MongoDB\\Collection::distinct`, and
:manual:`findAndModify </reference/command/findAndModify>` helpers do not
support a ``typeMap`` option due to a driver limitation.
:phpmethod:`MongoDB\\Collection::aggregate`,
:phpmethod:`MongoDB\\Collection::distinct`,
:phpmethod:`MongoDB\\Collection::findOneAndReplace`,
:phpmethod:`MongoDB\\Collection::findOneAndUpdate`, and
:phpmethod:`MongoDB\\Collection::findOneAndDelete`
return BSON documents as `stdClass` objects and arrays as arrays.
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBCollection__construct
/reference/method/MongoDBCollection-aggregate
/reference/method/MongoDBCollection-bulkWrite
/reference/method/MongoDBCollection-count
/reference/method/MongoDBCollection-createIndex
/reference/method/MongoDBCollection-createIndexes
/reference/method/MongoDBCollection-deleteMany
/reference/method/MongoDBCollection-deleteOne
/reference/method/MongoDBCollection-distinct
/reference/method/MongoDBCollection-drop
/reference/method/MongoDBCollection-dropIndex
/reference/method/MongoDBCollection-dropIndexes
/reference/method/MongoDBCollection-find
/reference/method/MongoDBCollection-findOne
/reference/method/MongoDBCollection-findOneAndDelete
/reference/method/MongoDBCollection-findOneAndReplace
/reference/method/MongoDBCollection-findOneAndUpdate
/reference/method/MongoDBCollection-getCollectionName
/reference/method/MongoDBCollection-getDatabaseName
/reference/method/MongoDBCollection-getNamespace
/reference/method/MongoDBCollection-insertMany
/reference/method/MongoDBCollection-insertOne
/reference/method/MongoDBCollection-listIndexes
/reference/method/MongoDBCollection-replaceOne
/reference/method/MongoDBCollection-updateMany
/reference/method/MongoDBCollection-updateOne
/reference/method/MongoDBCollection-withOptions
=======================
MongoDB\\Database Class
=======================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpclass:: MongoDB\\Database
Provides methods for common operations on a database,
such as executing database commands and managing collections.
You can construct a database directly using the PHP extension's
``Manager`` class or select a database from the |php-library|'s
:phpclass:`MongoDB\\Client`
class.
:phpclass:`MongoDB\\Database` supports the :php:`readConcern
<mongodb-driver-readconcern>`, :php:`readPreference
<mongodb-driver-readpreference>`, :php:`typeMap
<mongodb.persistence.php#mongodb.persistence.typemaps>`, and
:php:`writeConcern <mongodb-driver-writeconcern>` options.
If you omit an option, the database inherits the value from the
Manager constructor argument or the Client object used to select
the database.
Operations within the ``Database`` class
:phpmethod:`MongoDB\\Database::command` method
inherit the Database's options.
.. _database-methods:
Methods
-------
.. toctree::
:titlesonly:
/reference/method/MongoDBDatabase__get
/reference/method/MongoDBDatabase__construct
/reference/method/MongoDBDatabase-command
/reference/method/MongoDBDatabase-createCollection
/reference/method/MongoDBDatabase-drop
/reference/method/MongoDBDatabase-dropCollection
/reference/method/MongoDBDatabase-getDatabaseName
/reference/method/MongoDBDatabase-listCollections
/reference/method/MongoDBDatabase-selectCollection
/reference/method/MongoDBDatabase-withOptions
===============================
MongoDB\\Client::dropDatabase()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::dropDatabase($databaseName, $options)
Drop a MongoDB database.
.. code-block:: php
function dropDatabase($databaseName, array $options [])
:phpmethod:`MongoDB\\Client::dropDatabase` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-dropDatabase-param.rst
``dropDatabase`` supports the following values for the ``$options`` array:
.. include:: /includes/apiargs/MongoDBClient-method-dropDatabase-option.rst
Output
------
Returns an array or object containing the result document.
Example
-------
The following example drops the ``demo`` database:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$result = $client->dropDatabase('demo');
var_dump($result);
The ``dropDatabase`` operation would return an object similar to:
.. code-block:: php
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dropped"]=>
string(4) "demo"
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Client::drop`
- :manual:`dropDatabase() command reference
</reference/command/dropDatabase>` in the MongoDB manual.
================================
MongoDB\\Client::listDatabases()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::listDatabases($options)
Lists the available databases.
.. code-block:: php
function listDatabases(array $options = []): MongoDB\Model\DatabaseInfoIterator
:phpmethod:`MongoDB\\Client::listDatabases` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-param.rst
``listDatabases`` supports the following values for the ``$options`` array:
.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-option.rst
Output
------
Information for all databases on the :program:`mongod`, replica set,
or sharded cluster to which you are connected. The returned elements are
``MongoDB\Model\DatabaseInfo`` objects.
Example
-------
The following example lists all databases on the server:
.. code-block:: php
<?php
$client = new MongoDB\Client;
foreach ($client->listDatabases() as $databaseInfo) {
var_dump($databaseInfo);
}
The above example would output something similar to:
.. code-block:: php
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)
}
.. seealso::
:manual:`listDatabases() command reference in the MongoDB
manual </reference/command/listDatabases>`
===================================
MongoDB\\Client::selectCollection()
===================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::selectCollection($databaseName, $collectionName, $options)
Selects a collection on the :program:`mongod` to which your application
is connected.
.. code-block:: php
function selectCollection($databaseName, $collectionName, array $options = [])
:phpmethod:`MongoDB\\Client::selectCollection` has the following parameters:
.. include:: /includes/apiargs/common-param.rst
The following table describes the options that
:phpmethod:`MongoDB\\Client::selectCollection` can accept.
.. include:: /includes/apiargs/common-option.rst
Output
------
Returns a :phpclass:`MongoDB\\Collection` object.
Example
-------
The following example selects the ``users`` collection in the ``demo``
database:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$collection = $client->selectCollection('demo', 'users');
The following examples selects the ``users`` collection in the ``demo``
database with a custom read preference:
.. code-block:: php
$client = new MongoDB\Client;
$collection = $client->selectCollection(
'demo',
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
.. seealso::
- :phpmethod:`Collection::__construct`
- :phpmethod:`MongoDB\\Client::__get`
=================================
MongoDB\\Client::selectDatabase()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::selectDatabase($databaseName, $options)
Selects a database on the :program:`mongod` instance to which your
application is connected.
.. code-block:: php
function selectDatabase($databaseName array $options = []): MongoDB\Database
:phpmethod:`MongoDB\\Client::selectDatabase` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-selectDatabase-param.rst
The following table describes the options that
:phpmethod:`MongoDB\\Client::selectDatabase` can accept.
.. include:: /includes/apiargs/MongoDBClient-method-selectDatabase-option.rst
Output
------
Returns a :phpclass:`MongoDB\\Database` object.
Example
-------
The following example selects the ``demo`` database:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$db = $client->selectDatabase('demo');
The following examples selects the ``demo`` database with a custom read
preference:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$db = $client->selectDatabase(
'demo',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
.. seealso::
- :phpmethod:`Collection::__construct`
- :phpmethod:`MongoDB\\Client::__get`
==============================
MongoDB\\Client::__construct()
==============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::__construct($uri, $uriOptions, $driverOptions)
Constructs a new :phpclass:`Client <MongoDB\\Client>` instance.
.. code-block:: php
function __construct($uri = 'mongodb://localhost:27017', array $uriOptions = [], array $driverOptions = [])
:phpmethod:`MongoDB\\Client::__construct` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-construct-param.rst
Examples
--------
If you do not specify a ``$uri`` value, the driver connects to a
standalone :program:`mongod` on ``localhost`` via port ``27017``. The
following example demonstrates how to connect to a replica set
with a custom
read preference:
.. code-block:: php
<?php
$client = new MongoDB\Client(
'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet',
[
'readPreference' => 'secondaryPreferred'
]
);
By default, the |php-library| deserializes 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 :php:`mongo extension <mongo>`.
.. code-block:: php
<?php
$client = new MongoDB\Client(
null,
[],
[ 'typeMap' => [
'root' => 'array', 'document' => 'array', 'array' => 'array'
],
]
);
========================
MongoDB\\Client::__get()
========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Client::__get($databaseName)
Select a MongoDB database.
.. code-block:: php
function __get($databaseName): MongoDB\Database
:phpmethod:`MongoDB\\Client::__get` has the following parameters:
.. include:: /includes/apiargs/MongoDBClient-method-get-param.rst
Behavior
--------
The selected database inherits options such as read preference and
type mapping from the :phpclass:`Client <MongoDB\\Client>` object.
If you wish to override any options, use the
:phpmethod:`MongoDB\\Client::selectDatabase` method.
.. note::
To select databases whose names contain special characters, such as
``-``, use complex syntax, as in ``$client->{'that-database'}``.
Alternatively, :phpmethod:`MongoDB\\Client::selectDatabase` supports
selecting databases whose names contain special characters.
Examples
--------
The following example selects the ``demo`` and ``another-app``
databases:
.. code-block:: php
<?php
$client = new MongoDB\Client;
$demo = $client->demo;
$anotherApp = $client->{'another-app'};
.. seealso::
- :phpmethod:`MongoDB\\Client::selectDatabase`
- :php:`Property Overloading <oop5.overloading>` in the PHP Manual.
================================
MongoDB\\Collection::aggregate()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::aggregate($pipeline, $options)
Executes an :manual:`aggregation framework pipeline
</core/aggregation-pipeline/>` operation on the collection.
.. code-block:: php
function aggregate(array $pipeline, array $options = []): Traversable
:phpmethod:`MongoDB\\Collection::aggregate` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-aggregate-param.rst
:phpmethod:`MongoDB\\Collection::aggregate` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-aggregate-option.rst
.. _php-agg-method-output:
Output
------
:phpmethod:`MongoDB\\Collection::aggregate`'s return value depends on
the MongoDB server version and whether the ``useCursor`` option is
specified. If ``useCursor`` is true,
:phpmethod:`MongoDB\\Collection::aggregate` returns a
``MongoDB\Driver\Cursor`` object. If ``useCursor`` is false,
:phpmethod:`MongoDB\\Collection::aggregate` returns an
``ArrayIterator`` that 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`` option. Classes
implementing :php:`MongoDB\\BSON\\Persistable
<mongodb-bson-persistable>` will still be deserialized according to
the :php:`Persistence <mongodb.persistence.deserialization>`
specification.
.. todo: add examples
.. seealso::
- :manual:`aggregate command reference
</reference/command/aggregate>` in the MongoDB manual and
- :manual:`Aggregation Pipeline </core/aggregation-pipeline>`
documentation in the MongoDB Manual.
================================
MongoDB\\Collection::bulkWrite()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::bulkWrite($operations, $options)
Executes multiple write operations.
.. code-block:: php
function bulkWrite(array $operations, array $options = []): MongoDB\BulkWriteResult
:phpmethod:`MongoDB\\Collection::bulkWrite` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-bulkWrite-param.rst
:phpmethod:`MongoDB\\Collection::bulkWrite` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-bulkWrite-option.rst
.. todo: add output and examples
.. seealso::
- :phpmethod:`deleteMany <MongoDB\\Collection::deleteMany>`
- :phpmethod:`deleteOne <MongoDB\\Collection::deleteOne>`
- :phpmethod:`insertOne <MongoDB\\Collection::insertOne>`
- :phpmethod:`replaceOne <MongoDB\\Collection::replaceOne>`
- :phpmethod:`updateMany <MongoDB\\Collection::updateMany>`
- :phpmethod:`updateOne <MongoDB\\Collection::updateOne>`
- :doc:`/tutorial/crud`
============================
MongoDB\\Collection::count()
============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::count($filter, $options)
Counts the number of documents that match filter criteria.
.. code-block:: php
function count($filter = [], array $options = []): integer
:phpmethod:`MongoDB\\Collection::count` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-count-param.rst
:phpmethod:`MongoDB\\Collection::count` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-count-option.rst
.. todo: add output and examples
.. seealso::
- :manual:`count command reference </reference/command/count>`
in the MongoDB manual.
================================
MongoDBCollection::createIndex()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::createIndex($key, $options)
Create an index for the collection.
.. code-block:: php
function createIndex($key, array $options = []): string
``createIndex()`` accepts the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-createIndex-param.rst
The ``$options`` parameter accepts all index options that your
MongoDB version supports. MongoDB 3.2 includes the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-createIndex-option.rst
For a full list of the supported index creation options, refer to
the :manual:`createIndexes </reference/command/createIndexes>`
command reference in the MongoDB manual.
Output
------
Returns the name of the created index as a string.
Examples
--------
Create a Compound Index
~~~~~~~~~~~~~~~~~~~~~~~
The following operation creates a :manual:`compound index
</core/index-compound>` on the ``borough`` and ``cuisine`` fields
in the ``restaurants`` collection.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$keys = ['borough' => 1, 'cuisine' => 1];
$indexString = $collection->createIndex($keys, ['name' => 'compound']);
var_dump($indexString);
The output would resemble the following:
.. code-block:: none
string(8) "compound"
Create a Partial Index
~~~~~~~~~~~~~~~~~~~~~~
The following operation adds a :manual:`partial index
</core/index-parital>` on the ``borough`` field in the ``restaurants``
collection in the ``example`` database. The partial index indexes only
fields where the ``borough`` field exists.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$indexString = $collection->createIndex(
['borough' => 1],
['partialFilterExpression'=>
['borough'=>
['$exists'=>true]
]]);
var_dump($indexString);
The output would resemble::
string(9) "borough_1"
.. seealso::
- :phpmethod:`MongoDB\\Collection::createIndexes`
- :doc:`/tutorial/indexes`
- :manual:`createIndexes </reference/command/createIndexes>`
command reference in the MongoDB manual
- :manual:`Index documentation </indexes>`
==================================
MongoDBCollection::createIndexes()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::createIndexes($indexes)
Create one or more indexes for the collection.
.. code-block:: php
function createIndexes(array $indexes): string[]
``createIndex()`` has one parameter: ``$indexes``, which is an array
or object.
Each element in the ``$indexes`` array|object must have a
"``key`` document" that specifies the fields to index and the
array direction or type. You can then specify index options as
additional key-value pairs in that element.
For example, the following ``$indexes`` parameter creates an ascending
unique index on the ``username`` field:
.. code-block:: none
[ 'key' => ['username => 1 '], 'unique' => true ],
The following ``$indexes`` parameter creates a 2dsphere index on the ``loc`` field and
specifies a custom index name:
.. code-block:: none
[ 'key' => [ 'loc' => '2dsphere'], 'name' => 'geo_index' ],
You can specify any index options that your MongoDB version
supports. MongoDB 3.2 includes the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-createIndex-option.rst
For a full list of the supported index creation options, refer to
the :manual:`createIndexes </reference/command/createIndexes>`
command reference in the MongoDB manual.
Output
------
Returns the name of the created indexes as an array of strings.
Example
-------
The following creates two indexes on the ``restaurants`` collection in
the ``example`` database. One index is a compound index on the
``borough`` and ``cuisine`` fields and the other is 2dsphere index
on the ``location`` field with a custom name.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$index = $collection->createIndexes(
[
[ 'key' => [ 'borough' => 1, 'cuisine' => 1] ],
[ 'key' => [ 'location' => '2dsphere'], 'name' => 'geo_index'],
]);
var_dump($index);
The output would resemble the following::
array(2) {
[0]=>
string(19) "borough_1_cuisine_1"
[1]=>
string(9) "geo_index"
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::createIndex`
- :doc:`/tutorial/indexes`
- :manual:`createIndexes </reference/command/createIndexes>`
command reference in the MongoDB manual
- :manual:`Index documentation </indexes>`
=================================
MongoDB\\Collection::deleteMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::deleteMany($filter, $options)
Deletes all documents that match the filter criteria.
.. code-block:: php
function deleteMany($filter, array $options = []): MongoDB\DeleteResult
:phpmethod:`MongoDB\\Collection::deleteMany` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteMany-param.rst
:phpmethod:`MongoDB\\Collection::deleteMany` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteMany-option.rst
Output
------
Returns a ``MongoDB\DeleteResult`` object.
Example
-------
The following operation deletes all of the documents in the ``users``
collection that have ``ny`` as the value for the ``state`` field:
.. code-block:: php
<?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 output would then resemble::
Deleted 2 document(s)
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::deleteOne`
- :doc:`/tutorial/crud`
- :manual:`delete command reference </reference/command/delete`
in the MongoDB manual
\ No newline at end of file
================================
MongoDB\\Collection::deleteOne()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::deleteOne($filter, $options)
Deletes at most one document that matches the filter criteria. If
multiple documents match the filter criteria,
:phpmethod:`MongoDB\\Collection::deleteOne` deletes the :term:`first
<natural order>` matching document.
.. code-block:: php
function deleteOne($filter, array $options = []): MongoDB\DeleteResult
:phpmethod:`MongoDB\\Collection::deleteMany` has the following
parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteOne-param.rst
:phpmethod:`MongoDB\\Collection::deleteMany` supports the following
options:
.. include:: /includes/apiargs/MongoDBCollection-method-deleteOne-option.rst
Output
------
Returns a ``MongoDB\DeleteResult`` object.
Example
-------
The following operation deletes the first documents in the ``users``
collection that has ``ny`` as the value for the ``state`` field:
.. code-block:: php
<?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 output would then resemble::
Deleted 1 document(s)
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::deleteMany`
- :doc:`/tutorial/crud`
- :manual:`delete command reference </reference/command/delete`
in the MongoDB manual
\ No newline at end of file
===============================
MongoDB\\Collection::distinct()
===============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::distinct()
Finds the distinct values for a specified field across the collection.
.. code-block:: php
function distinct($fieldName, $filter = [], array $options = []): mixed[]
``distinct`` has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-distinct-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-distinct-option.rst
Output
------
Returns an array of the distinct values.
Examples
--------
Return Distinct Values for a Field
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following example identifies the distinct values for the
``borough`` field in the ``restaurants`` collection in the
``example`` database.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$distinct = $collection->distinct('borough');
var_dump($distinct);
The output would resemble::
array(6) {
[0]=>
string(5) "Bronx"
[1]=>
string(8) "Brooklyn"
[2]=>
string(9) "Manhattan"
[3]=>
string(7) "Missing"
[4]=>
string(6) "Queens"
[5]=>
string(13) "Staten Island"
}
Return Distinct Values Using a Filter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following example identifies the distinct values for the
``cuisine`` field in the ``restaurants`` collection in the ``example``
database for documents where the ``borough`` is ``Queens``:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$distinct = $collection->distinct('cuisine', ['borough'=>'Queens']);
var_dump($distinct);
The output would then resemble::
array(75) {
[0]=>
string(6) "Afghan"
[1]=>
string(7) "African"
[2]=>
string(9) "American "
[3]=>
string(8) "Armenian"
[4]=>
string(5) "Asian"
[5]=>
string(10) "Australian"
[6]=>
string(15) "Bagels/Pretzels"
[7]=>
string(6) "Bakery"
[8]=>
string(11) "Bangladeshi"
[9]=>
string(8) "Barbecue"
[10]=>
string(55) "Bottled beverages, including water, sodas, juices, etc."
[11]=>
string(9) "Brazilian"
[12]=>
string(4) "Cafe"
[13]=>
string(16) "Café/Coffee/Tea"
[14]=>
string(5) "Cajun"
[15]=>
string(9) "Caribbean"
[16]=>
string(7) "Chicken"
[17]=>
string(7) "Chinese"
[18]=>
string(13) "Chinese/Cuban"
[19]=>
string(16) "Chinese/Japanese"
[20]=>
string(11) "Continental"
[21]=>
string(6) "Creole"
[22]=>
string(5) "Czech"
[23]=>
string(12) "Delicatessen"
[24]=>
string(6) "Donuts"
[25]=>
string(16) "Eastern European"
[26]=>
string(8) "Egyptian"
[27]=>
string(7) "English"
[28]=>
string(8) "Filipino"
[29]=>
string(6) "French"
[30]=>
string(17) "Fruits/Vegetables"
[31]=>
string(6) "German"
[32]=>
string(5) "Greek"
[33]=>
string(10) "Hamburgers"
[34]=>
string(16) "Hotdogs/Pretzels"
[35]=>
string(31) "Ice Cream, Gelato, Yogurt, Ices"
[36]=>
string(6) "Indian"
[37]=>
string(10) "Indonesian"
[38]=>
string(5) "Irish"
[39]=>
string(7) "Italian"
[40]=>
string(8) "Japanese"
[41]=>
string(13) "Jewish/Kosher"
[42]=>
string(30) "Juice, Smoothies, Fruit Salads"
[43]=>
string(6) "Korean"
[44]=>
string(64) "Latin (Cuban, Dominican, Puerto Rican, South & Central American)"
[45]=>
string(13) "Mediterranean"
[46]=>
string(7) "Mexican"
[47]=>
string(14) "Middle Eastern"
[48]=>
string(8) "Moroccan"
[49]=>
string(25) "Not Listed/Not Applicable"
[50]=>
string(18) "Nuts/Confectionary"
[51]=>
string(5) "Other"
[52]=>
string(9) "Pakistani"
[53]=>
string(16) "Pancakes/Waffles"
[54]=>
string(8) "Peruvian"
[55]=>
string(5) "Pizza"
[56]=>
string(13) "Pizza/Italian"
[57]=>
string(6) "Polish"
[58]=>
string(10) "Portuguese"
[59]=>
string(7) "Russian"
[60]=>
string(6) "Salads"
[61]=>
string(10) "Sandwiches"
[62]=>
string(30) "Sandwiches/Salads/Mixed Buffet"
[63]=>
string(7) "Seafood"
[64]=>
string(9) "Soul Food"
[65]=>
string(18) "Soups & Sandwiches"
[66]=>
string(12) "Southwestern"
[67]=>
string(7) "Spanish"
[68]=>
string(5) "Steak"
[69]=>
string(5) "Tapas"
[70]=>
string(7) "Tex-Mex"
[71]=>
string(4) "Thai"
[72]=>
string(7) "Turkish"
[73]=>
string(10) "Vegetarian"
[74]=>
string(29) "Vietnamese/Cambodian/Malaysia"
}
.. seealso::
- :manual:`distinct </reference/command/distinct>` command
reference in the MongoDB manual.
===========================
MongoDB\\Collection::drop()
===========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::drop
Drops the collection.
.. code-block:: php
function drop(array $options = []): array|object
``drop()`` supports the following parameter:
.. include:: /includes/apiargs/MongoDBCollection-method-drop-param.rst
The ``$options`` parameter supports the following option:
.. include:: /includes/apiargs/MongoDBCollection-method-drop-option.rst
Output
------
Returns the command result document as an array or object, depending
on the ``typeMap`` specification.
Example
-------
The following operation drops the ``restaurants`` collection in the
``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$output = $collection->drop();
var_dump($output);
The output would resemble::
object(MongoDB\Model\BSONDocument)#9 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["ns"]=>
string(19) "example.restaurants"
["nIndexesWas"]=>
int(3)
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Database::dropCollection`
- :manual:`drop </reference/command/drop>` command reference in
the MongoDB manual.
================================
MongoDB\\Collection::dropIndex()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::dropIndex($indexName, $options)
Drops an index from the collection.
.. code-block:: php
function dropIndex($indexName, array $options = []): array|object
``dropIndex()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-param.rst
The ``$options`` parameter supports the following option:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-option.rst
Output
------
Returns the command result document as an array or object, depending
on the ``typeMap`` specification.
Example
-------
The following drops an indexes with name ``borough_1`` from the
``restaurants`` collection in the ``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$index = $collection->dropIndex( "borough_1" );
var_dump($index);
The output would resemble the following::
object(MongoDB\Model\BSONDocument)#9 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::dropIndexes`
- :doc:`/tutorial/indexes`
- :manual:`dropIndexes </reference/command/dropIndexes>` command
references in the MongoDB manual.
- :manual:`Index documentation </indexes>`
==================================
MongoDB\\Collection::dropIndexes()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::dropIndexes($options)
Drops **all indexes** in the collection.
.. code-block:: php
function dropIndexes(array $options = []): array|object
``dropIndexes()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-param.rst
The ``$options`` parameter supports the following option:
.. include:: /includes/apiargs/MongoDBCollection-method-dropIndex-option.rst
Output
------
Returns the command result document as an array or object, depending
on the ``typeMap`` specification.
Example
-------
The following drops all indexes from the ``restaurants`` collection in
the ``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$response = $collection->dropIndexes();
var_dump($response);
The output would resemble the following::
object(MongoDB\Model\BSONDocument)#9 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["nIndexesWas"]=>
int(3)
["msg"]=>
string(38) "non-_id indexes dropped for collection"
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::dropIndex`
- :doc:`/tutorial/indexes`
- :manual:`dropIndexes </reference/command/dropIndexes>` command
references in the MongoDB manual.
- :manual:`Index documentation </indexes>`
===========================
MongoDB\\Collection::find()
===========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::find
Finds documents matching the query.
.. code-block:: php
function find($filter = [], array $options = []): MongoDB\Driver\Cursor
``find()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-find-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-find-option.rst
Output
------
Returns a ``MongoDB\Driver\Cursor`` object.
Examples
--------
The following example finds restaurants based on the ``cuisine`` and
``borough`` fields and uses a :manual:`projection
</tutorial/project-fields-from-query-results>` to limit the fields
that are returned. It also limits the results to 5 documents.
.. code-block:: php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$restaurants = $collection->find(
[ 'cuisine' => 'Italian', 'borough' => 'Manhattan' ],
[ 'limit' => 5,
'projection' => [
'name' => 1, 'borough' => 1, 'cuisine' => 1,
],
]
);
foreach ($restaurants as $restaurant) {
var_dump($restaurant);
};
The output would resemble:
.. code-block:: none
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#8 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f983"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(23) "Isle Of Capri Resturant"
}
}
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#12 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f98d"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(18) "Marchis Restaurant"
}
}
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#10 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f99b"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(19) "Forlinis Restaurant"
}
}
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#13 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f9a8"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(22) "Angelo Of Mulberry St."
}
}
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#8 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f9b4"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(16) "V & T Restaurant"
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOne`
- :manual:`find </reference/command/find>` command reference
in the MongoDB manual
==============================
MongoDB\\Collection::findOne()
==============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::findOne
Finds a single document matching the query.
.. code-block:: php
function findOne($filter = [], array $options = []): array|object
``findOne()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-findOne-option.rst
Output
------
Returns the :term:`first document <natural order>` that matches the
query or ``null`` if no document matches the query.
Examples
--------
The following example finds a restaurant based on the ``cuisine`` and
``borough`` fields and uses a :manual:`projection
</tutorial/project-fields-from-query-results>` to limit the fields
that are returned.
.. code-block:: php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$restaurants = $collection->findOne(
[ 'cuisine' => 'Italian', 'borough' => 'Manhattan'],
[ 'limit' => 5,
'projection' => [
'name' => 1, 'borough' => 1, 'cuisine' => 1,
],
]
);
foreach ($restaurants as $restaurant) {
var_dump($restaurant);
};
The output would resemble:
.. code-block:: none
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f983"
}
string(9) "Manhattan"
string(7) "Italian"
string(23) "Isle Of Capri Resturant"
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOne`
- :manual:`find </reference/command/find>` command reference
in the MongoDB manual
=======================================
MongoDB\\Collection::findOneAndDelete()
=======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::findOneAndDelete
Finds a single document and deletes it.
.. code-block:: php
function findOneAndDelete($filter = [], array $options = []): object|null
``findOne()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndDelete-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndDelete-option.rst
.. include:: /includes/extracts/bson-deserialization-findOneAndDelete.rst
Output
------
Returns the document that was deleted. If no document matched the
filter, the returned document is ``null``.
Examples
--------
The following example deletes the document with ``restaurant_id`` of
``40375376`` from the ``restaurants`` collection in the ``example``
database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$deletedRestaurant = $collection->findOneAndDelete(
[ 'restaurant_id' => '40375376' ],
[ 'projection' => [ 'name' => 1,
'borough' => 1,
'restaurant_id' => 1
]
]
);
The output would resemble:
.. code-block:: none
object(stdClass)#14 (4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3fad9"
}
["borough"]=>
string(9) "Manhattan"
["name"]=>
string(15) "Agra Restaurant"
["restaurant_id"]=>
string(8) "40375376"
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOneAndUpdate`
- :phpmethod:`MongoDB\\Collection::findOneAndReplace`
- :manual:`findAndModify </reference/command/findAndModify>`
command reference in the MongoDB manual
========================================
MongoDB\\Collection::findOneAndReplace()
========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::findOneAndReplace
Finds a single document matching the query and replaces it.
.. code-block:: php
function findOneAndReplace($filter, $replacement, array $options = []): object|null
``findOneAndReplace()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndReplace-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndReplace-option.rst
.. include:: /includes/extracts/bson-deserialization-findOneAndReplace.rst
Output
------
By default, returns the original document. To return the *new*
document, use the ``returnDocument`` option. If no document matched
the query, returns ``null``.
Examples
--------
Consider the following document in the ``restaurants`` collection in
the ``example`` database:
.. code-block:: javascript
{
"_id" : ObjectId("576023c7b02fa9281da4139e"),
"address" : {
"building" : "977",
"coord" : [
-74.06940569999999,
40.6188443
],
"street" : "Bay Street",
"zipcode" : "10305"
},
"borough" : "Staten Island",
"cuisine" : "French",
"grades" : [
{
"date" : ISODate("2014-08-15T00:00:00Z"),
"grade" : "A",
"score" : 7
},
{
"date" : ISODate("2014-02-13T00:00:00Z"),
"grade" : "A",
"score" : 5
},
{
"date" : ISODate("2013-06-07T00:00:00Z"),
"grade" : "A",
"score" : 11
}
],
"name" : "Zest",
"restaurant_id" : "41220906"
}
The following operation replaces the document with ``restaurant_id :
41220906`` with the new specified document:
.. code-block:: php
<?php
$collection = $database->selectCollection('example','restaurants');
$updateRestaurant = $collection->findOneAndReplace(
[ 'restaurant_id' => '41220906' ],
[ 'Borough' => 'Staten Island',
'cuisine' => 'Italian',
'grades' => [],
'name' => 'Staten Island Pastaria',
'restaurant_id' => '999999999',
],
[ 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER ]
);
var_dump($updateRestaurant)
The ``var_dump()`` output contains the new document, as in the following::
object(stdClass)#14 (6) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "576023c7b02fa9281da4139e"
}
["borough"]=>
string(13) "Staten Island"
["cuisine"]=>
string(7) "Italian"
["grades"]=>
array(0) {
}
["name"]=>
string(22) "Staten Island Pastaria"
["restaurant_id"]=>
string(9) "999999999"
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOneAndDelete`
- :phpmethod:`MongoDB\\Collection::findOneAndUpdate`
- :manual:`findAndModify </reference/command/findAndModify>`
command reference in the MongoDB manual
=======================================
MongoDB\\Collection::findOneAndUpdate()
=======================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::findOneAndUpdate
Finds a single document matching the query and updates it.
.. code-block:: php
function findOneAndUpdate($filter, $update, array $options = []): object|null
``findOneAndUpdate()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndUpdate-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-findOneAndUpdate-option.rst
.. include:: /includes/extracts/bson-deserialization-findOneAndUpdate.rst
Output
------
Returns either the original or the updated document, depending on the
specified value for the ``returnDocument`` option. By default, the
original document is returned.
Examples
--------
The following operation updates the building number of the restaurant
with ``restaurant_id : 40361708`` in the ``restaurants`` collection in
the ``example`` database to ``761``:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$updateRestaurant = $collection->findOneAndUpdate(
[ 'restaurant_id' => '40361708' ],
[ '$set' => ['address.building' => '761']],
[ 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER ]
);
var_dump($updateRestaurant)
.. seealso::
- :phpmethod:`MongoDB\\Collection::findOneAndDelete`
- :phpmethod:`MongoDB\\Collection::findOneAndReplace`
- :manual:`findAndModify </reference/command/findAndModify>` command reference
in the MongoDB manual
========================================
MongoDB\\Collection::getCollectionName()
========================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Collection::getCollectionName()
Returns the name of the current collection.
.. code-block:: php
function getCollectionName(): string
Example
-------
The following returns the name of the collection assigned to the
``$collection`` variable
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
echo $collection->getCollectionName();
The ``$collection`` variable uses the :phpmethod:`constructor
<MongoDB\\Collection::__construct>` method to select the ``zips``
collection in the ``demo`` database, as such, the printed output would
resemble:
.. code-block:: none
zips
======================================
MongoDB\\Collection::getDatabaseName()
======================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Collection::getDatabaseName()
Returns the name of the current database.
.. code-block:: php
function getDatabaseName(): string
Example
-------
The following returns the name of the database of the collection
assigned to the ``$collection`` variable
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
echo $collection->getDatabaseName();
The ``$collection`` variable uses the :phpmethod:`constructor
<MongoDB\\Collection::__construct>` method to select the ``zips``
collection in the ``demo`` database, as such, the printed output would
resemble:
.. code-block:: none
demo
===================================
MongoDB\\Collection::getNamespace()
===================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Collection::getNamespace()
Returns the :term:`namespace` of the collection. A namespace
is the canonical name of an index or collection in MongoDB.
.. code-block:: php
function getNamespace(): string
Example
-------
The following returns the namespace of the collection
assigned to the ``$collection`` variable
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
echo $collection->getNamespace();
The ``$collection`` variable uses the :phpmethod:`constructor
<MongoDB\\Collection::__construct>` method to select the ``zips``
collection in the ``demo`` database, as such, the printed output would
resemble:
.. code-block:: none
demo.zips
=================================
MongoDB\\Collection::insertMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::insertMany
Inserts one document.
.. code-block:: php
function insertMany(array $documents, array $options = []): MongoDB\InsertManyResult
``insertMany()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-insertMany-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-insertMany-option.rst
Output
------
Returns a ``MongoDB\InsertManyResult`` object.
Example
-------
.. start-crud-include
The following operation inserts two documents into the ``users``
collection in the ``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('users','restaurants');
$newUsers = $collection->insertMany(
[
[
'username' => 'admin',
'email' => 'admin@example.com',
'name' => 'Admin User'
],
[
'username' => 'test',
'email' => 'test@example.com',
'name' => 'Test User'
],
]
);
printf("Inserted %d document(s)\n", $newUsers->getInsertedCount());
var_dump($newUsers->getInsertedIds());
The output would resemble::
Inserted 2 document(s)
array(2) {
[0]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "579a25921f417dd1e5518141"
}
[1]=>
object(MongoDB\BSON\ObjectID)#12 (1) {
["oid"]=>
string(24) "579a25921f417dd1e5518142"
}
}
.. end-crud-include
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::insertOne`
- :doc:`/tutorial/crud`
- :manual:`insert </reference/command/insert>` command reference
in the MongoDB manual
================================
MongoDB\\Collection::insertOne()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::insertOne
Inserts one document.
.. code-block:: php
function insertOne($document, array $options = []): MongoDB\InsertOneResult
``insertOne()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-insertOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-insertOne-option.rst
Output
------
Returns a ``MongoDB\InsertOneResult`` object.
Example
-------
The following operation inserts a document into the ``users``
collection in the ``example`` database:
.. include:: /includes/example-insertOne.rst
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::insertMany`
- :doc:`/tutorial/crud`
- :manual:`insert </reference/command/insert>` command reference
in the MongoDB manual
==================================
MongoDB\\Collection::listIndexes()
==================================
.. default-domain:: mongodb
.. contents::
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::listIndexes($options)
Returns information for all indexes for the collection.
.. code-block:: php
function listIndexes(array $options = []): MongoDB\Model\IndexInfoIterator
:phpmethod:`MongoDB\\Collection::listIndexes` supports the
following parameter:
.. include:: /includes/apiargs/MongoDBCollection-method-listIndexes-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-listIndexes-option.rst
Output
------
Elements in the returned iterator are ``MongoDB\Model\IndexInfo``
objects.
Example
-------
The following lists information about the indexes on the collection
assigned to the ``$collection`` variable
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$indexes = $collection->listIndexes();
foreach ($indexes as $index) {
var_dump($index);
}
The output would then resemble::
object(MongoDB\Model\IndexInfo)#8 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["_id"]=>
int(1)
}
["name"]=>
string(4) "_id_"
["ns"]=>
string(19) "example.restaurants"
}
object(MongoDB\Model\IndexInfo)#12 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["cuisine"]=>
float(-1)
}
["name"]=>
string(10) "cuisine_-1"
["ns"]=>
string(19) "example.restaurants"
}
object(MongoDB\Model\IndexInfo)#8 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["borough"]=>
float(1)
}
["name"]=>
string(9) "borough_1"
["ns"]=>
string(19) "example.restaurants"
}
.. seealso::
- :doc:`/tutorial/indexes`
- :manual:`listIndexes command </reference/command/listIndexes>` in the MongoDB manual.
- :manual:`Index documentation </core/indexes>` in the MongoDB manual.
- `MongoDB Specification: Enumerating Collections
<https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst>`_
=================================
MongoDB\\Collection::replaceOne()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::replaceOne
Replaces at most one document that matches the filter.
.. code-block:: php
function replaceOne($filter, $replacement, array $options = []): MongoDB\UpdateResult
``replaceOne()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-replaceOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-replaceOne-option.rst
Output
------
Returns a ``MongoDB\UpdateResult`` object.
Example
-------
The following operation replaces the document with ``restaurant_id``
``40356068`` in the ``restaurants`` collection in the ``example`` database:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('users','restaurants');
$replacement = $collection->replaceOne(
[ 'restaurant_id' => '40356068'],
[
'name' => 'New Restaurant',
'restaurant_id' => '99988877',
'borough' => 'Queens',
'cuisine' => 'Cafe',
'grades' => [],
]
);
var_dump($replacement);
The output would resemble:
.. code-block:: none
object(MongoDB\UpdateResult)#13 (2) {
["writeResult":"MongoDB\UpdateResult":private]=>
object(MongoDB\Driver\WriteResult)#12 (9) {
["nInserted"]=>
int(0)
["nMatched"]=>
int(1)
["nModified"]=>
int(1)
["nRemoved"]=>
int(0)
["nUpserted"]=>
int(0)
["upsertedIds"]=>
array(0) {
}
["writeErrors"]=>
array(0) {
}
["writeConcernError"]=>
NULL
["writeConcern"]=>
array(4) {
["w"]=>
NULL
["wmajority"]=>
bool(false)
["wtimeout"]=>
int(0)
["journal"]=>
NULL
}
}
["isAcknowledged":"MongoDB\UpdateResult":private]=>
bool(true)
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::updateMany`
- :phpmethod:`MongoDB\\Collection::updateOne`
- :doc:`/tutorial/crud`
- :manual:`update </reference/command/update>` command reference
in the MongoDB manual
=================================
MongoDB\\Collection::updateMany()
=================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::updateMany
Updates all documents that match the filter criteria.
.. code-block:: php
function updateMany($filter, $update, array $options = []): MongoDB\UpdateResult
``updateMany()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-updateMany-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-updateMany-option.rst
Output
------
Returns a ``MongoDB\UpdateResult`` object.
Examples
--------
The following operation adds a an ``active`` field to all of the documents
with ``borough: Queens`` with value ``true``:
.. code-block:: php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$update = $collection->updateMany(
[ 'borough' => 'Queens'],
[
'$set' => [
'active' => 'True'
]
]
);
var_dump($update);
The output would then resemble::
object(MongoDB\UpdateResult)#13 (2) {
["writeResult":"MongoDB\UpdateResult":private]=>
object(MongoDB\Driver\WriteResult)#12 (9) {
["nInserted"]=>
int(0)
["nMatched"]=>
int(5656)
["nModified"]=>
int(5656)
["nRemoved"]=>
int(0)
["nUpserted"]=>
int(0)
["upsertedIds"]=>
array(0) {
}
["writeErrors"]=>
array(0) {
}
["writeConcernError"]=>
NULL
["writeConcern"]=>
array(4) {
["w"]=>
NULL
["wmajority"]=>
bool(false)
["wtimeout"]=>
int(0)
["journal"]=>
NULL
}
}
["isAcknowledged":"MongoDB\UpdateResult":private]=>
bool(true)
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::replaceOne`
- :phpmethod:`MongoDB\\Collection::updateOne`
- :doc:`/tutorial/crud`
- :manual:`update </reference/command/update>` command reference
in the MongoDB manual.
================================
MongoDB\\Collection::updateOne()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::updateOne
Finds a single document matching the query and updates it.
.. code-block:: php
function updateOne($filter, $update, array $options = []): MongoDB\UpdateResult
``updateOne()`` supports the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-updateOne-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-updateOne-option.rst
Output
------
Returns a ``MongoDB\UpdateResult`` object.
Examples
--------
The following operation updates the ``name`` of the restaurant with
``restaurant_id: 40356151`` to "Brunos on Astoria":
.. code-block:: php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$update = $collection->updateOne(
[ 'restaurant_id' => '40356151'],
[
'$set' => [
'name' => 'Brunos on Astoria'
]
]
);
var_dump($update);
The output would then resemble::
object(MongoDB\UpdateResult)#13 (2) {
["writeResult":"MongoDB\UpdateResult":private]=>
object(MongoDB\Driver\WriteResult)#12 (9) {
["nInserted"]=>
int(0)
["nMatched"]=>
int(1)
["nModified"]=>
int(1)
["nRemoved"]=>
int(0)
["nUpserted"]=>
int(0)
["upsertedIds"]=>
array(0) {
}
["writeErrors"]=>
array(0) {
}
["writeConcernError"]=>
NULL
["writeConcern"]=>
array(4) {
["w"]=>
NULL
["wmajority"]=>
bool(false)
["wtimeout"]=>
int(0)
["journal"]=>
NULL
}
}
["isAcknowledged":"MongoDB\UpdateResult":private]=>
bool(true)
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::bulkWrite`
- :phpmethod:`MongoDB\\Collection::replaceOne`
- :phpmethod:`MongoDB\\Collection::updateMany`
- :doc:`/tutorial/crud`
- :manual:`update </reference/command/update>` command reference
in the MongoDB manual.
==================================
MongoDB\\Collection::withOptions()
==================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Collection::withOptions($options)
Returns a clone of the collection, but with different options.
.. code-block:: php
function withOptions(array $options = []): MongoDB\Collection
:phpmethod:`MongoDB\\Collection::withOptions` supports the
following parameter:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-option.rst
Example
-------
The following example creates a new collection based on the
``restaurants`` collection in the ``example`` database with a custom
read preference:
.. code-block:: php
<?php
$database = new MongoDB\Client;
$sourceCollection = $database->selectCollection('example','restaurants');
$newCollection = $sourceCollection->withOptions([
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]);
.. seealso::
- :phpmethod:`MongoDB\\Collection::__construct`
==================================
MongoDB\\Collection::__construct()
==================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Collection::__construct($manager, $databaseName, $collectionName, $options)
Constructs a new :phpclass:`Collection <MongoDB\\Collection>` instance.
.. code-block:: php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, $collectionName, array $options = [])
:phpmethod:`MongoDB\\Collection::__construct` has the following parameters:
.. include:: /includes/apiargs/MongoDBCollection-method-construct-param.rst
:phpmethod:`MongoDB\\Collection::__construct` supports the following
options:
.. include:: /includes/apiargs/common-option.rst
If you construct the Collection explicitly, the Collection inherits
any options from the ``Manager`` object. If you select the Collection
from a :phpclass:`Client <MongoDB\\Client>` or :phpclass:`Database
<MongoDB\\Database>` object, the Collection inherits its options
from that object.
.. todo: add an example
.. seealso::
- :phpmethod:`MongoDB\\Collection::withOptions`
- :phpmethod:`MongoDB\\Database::selectCollection`
============================
MongoDB\\Database::command()
============================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::command
Execute a :manual:`command </reference/command>` on the database.
.. code-block:: php
function command($command, array $options = []): MongoDB\Driver\Cursor
:phpmethod:`MongoDB\\Database::command` has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-command-param.rst
``command`` supports the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-command-option.rst
Example
-------
The following operation creates a new user in the database using
the :dbcommand:`createUser` command:
.. code-block:: php
$database = (new MongoDB\Client)->example;
$newUser = $database->command(
[
'createUser' => 'admin',
'pwd' => 'admin123',
'roles' => [
'readWrite'
]
]
);
var_dump($newUser);
The output would resemble::
object(MongoDB\Driver\Cursor)#10 (2) {
["cursor"]=>
array(17) {
["stamp"]=>
int(0)
["is_command"]=>
bool(true)
["sent"]=>
bool(true)
["done"]=>
bool(false)
["end_of_event"]=>
bool(false)
["in_exhaust"]=>
bool(false)
["has_fields"]=>
bool(false)
["query"]=>
object(stdClass)#9 (3) {
["createUser"]=>
string(5) "admin"
["pwd"]=>
string(8) "admin123"
["roles"]=>
array(1) {
[0]=>
string(9) "readWrite"
}
}
["fields"]=>
object(stdClass)#3 (0) {
}
["read_preference"]=>
array(2) {
["mode"]=>
int(1)
["tags"]=>
array(0) {
}
}
["flags"]=>
int(0)
["skip"]=>
int(0)
["limit"]=>
int(1)
["count"]=>
int(1)
["batch_size"]=>
int(0)
["ns"]=>
string(12) "example.$cmd"
["current_doc"]=>
object(stdClass)#8 (1) {
["ok"]=>
float(1)
}
}
["server_id"]=>
int(1)
}
.. seealso::
- :doc:`/tutorial/commands`
- :manual:`Database Commands </reference/command>` in the
MongoDB manual
=====================================
MongoDB\\Database::createCollection()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::createCollection
Explicitly creates a collection.
.. code-block:: php
function createCollection($collectionName, array $options = []): array|object
MongoDB creates collections implicitly when you first reference
the collection in a command, such as when inserting a document
into a new collection. You may also explicitly create a collection
with specific options using the ``createCollection()``
method, or using :dbcommand:`create` in the :program:`mongo` shell.
Explicitly creating collections enables you to create
:manual:`capped collections </core/capped-collections>`, specify
:manual:`document validation criteria </core/document-validation>`,
or configure your storage engine or indexing options.
:phpmethod:`MongoDB\\Database::createCollection` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-createCollection-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-createCollection-option.rst
Note that not all options are available on all versions of MongoDB.
Document Validation, for example, was added in MongoDB 3.2;
similarly, the WiredTiger storage engine is available only for
MongoDB 3.0 and later. Refer to the :manual:`create command
</reference/command/create>` reference in the MongoDB manual for
compatibility considerations.
Output
------
Returns the command result document as an array.
Example
-------
The following example creates a ``users`` collection in the ``demo``
database with document validation criteria:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$result = $db->createCollection('users', [
'validator' => [
'username' => ['$type' => 'string'],
'email' => ['$regex' => '@mongodb\.com$'],
],
]);
var_dump($result);
The output would then resemble::
Object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
.. seealso::
:manual:`create </reference/command/create>` command reference in
the MongoDB manual
=========================
MongoDB\\Database::drop()
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::drop
Drops the database.
.. code-block:: php
function dropCollection($collectionName, array $options = []): array|object
:phpmethod:`MongoDB\\Database::drop` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-drop-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-drop-option.rst
Output
------
Returns the command result document as an array.
Example
-------
The following example drops the ``demo`` database:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$result = $db->drop();
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dropped"]=>
string(4) "demo"
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Client::dropDatabase`
- :manual:`dropDatabase </reference/command/dropDatabase>` command
reference in the MongoDB manual
===================================
MongoDB\\Database::dropCollection()
===================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::dropCollection
Drop a collection within the current database.
.. code-block:: php
function dropCollection($collectionName, array $options = []): array|object
:phpmethod:`MongoDB\\Database::dropCollection` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-dropCollection-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-dropCollection-option.rst
Output
------
Returns the command result document as an array.
Example
-------
The following example drops the ``users`` collection in the ``demo``
database:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$result = $db->dropCollection('users');
var_dump($result);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(3) {
["ns"]=>
string(10) "demo.users"
["nIndexesWas"]=>
int(1)
["ok"]=>
float(1)
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::drop`
- :manual:`drop </reference/command/drop>` command reference in
the MongoDB manual
====================================
MongoDB\\Database::getDatabaseName()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::getDatabaseName
Drops the database.
.. code-block:: php
function getDatabaseName(): string
Output
------
Returns the name of the database as a string.
Example
-------
The following example gets the name of the database from the ``$db``
variable:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
echo $db->getDatabaseName();
The output would then resemble::
demo
====================================
MongoDB\\Database::listCollections()
====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::listCollections
Returns information for all collections in this database.
.. code-block:: php
function listCollections(array $options=[]): MongoDB\Model\CollectionInfoIterator
:phpmethod:`MongoDB\\Database::listCollections` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-option.rst
Output
------
Returns information for all collections in the database. The elements
in the returned iterator are ``MongoDB\Model\CollectionInfo`` objects.
Example
-------
The following example lists all of the collections in the ``example``
database:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->example;
foreach ($database->listCollections() as $collectionInfo) {
var_dump($collectionInfo);
}
The output would then resemble::
object(MongoDB\Model\CollectionInfo)#3 (2) {
["name"]=>
string(11) "restaurants"
["options"]=>
array(0) {
}
}
object(MongoDB\Model\CollectionInfo)#11 (2) {
["name"]=>
string(5) "users"
["options"]=>
array(0) {
}
}
object(MongoDB\Model\CollectionInfo)#3 (2) {
["name"]=>
string(6) "restos"
["options"]=>
array(0) {
}
}
.. seealso::
- :manual:`listCollections </reference/command/listCollections`
command reference in the MongoDB manual.
- MongoDB Specification `Enumerating Collections
<https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst>`_
\ No newline at end of file
=====================================
MongoDB\\Database::selectCollection()
=====================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::selectCollection
Selects a collection within the database. The collection inherits
options such as read preference and type map from the Database object
unless otherwise specified in the ``$options`` parameter.
.. code-block:: php
function selectCollection($collectionName, array $options = []): MongoDB\Collection
:phpmethod:`MongoDB\\Database::selectCollection` has the following
parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-param.rst
The ``$options`` parameter accepts the following options:
.. include:: /includes/apiargs/MongoDBDatabase-method-selectCollection-option.rst
Output
------
Returns a :phpclass:`MongoDB\\Collection` object.
Example
-------
The following example selects the ``users`` collection in the ``demo``
database with a custom read preference:
.. code-block:: php
$db = (new MongoDB\Client)->demo;
$users = $db->selectCollection(
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
var_dump($users);
The output would then resemble::
object(MongoDB\Collection)#8 (7) {
["collectionName"]=>
string(5) "users"
["databaseName"]=>
string(4) "demo"
["manager"]=>
object(MongoDB\Driver\Manager)#2 (2) {
["uri"]=>
string(25) "mongodb://localhost:27017"
["cluster"]=>
array(1) {
[0]=>
array(11) {
["host"]=>
string(9) "localhost"
["port"]=>
int(27017)
["type"]=>
int(0)
["is_primary"]=>
bool(false)
["is_secondary"]=>
bool(false)
["is_arbiter"]=>
bool(false)
["is_hidden"]=>
bool(false)
["is_passive"]=>
bool(false)
["tags"]=>
array(0) {
}
["last_is_master"]=>
array(0) {
}
["round_trip_time"]=>
int(-1)
}
}
}
["readConcern"]=>
object(MongoDB\Driver\ReadConcern)#5 (1) {
["level"]=>
NULL
}
["readPreference"]=>
object(MongoDB\Driver\ReadPreference)#3 (2) {
["mode"]=>
int(2)
["tags"]=>
array(0) {
}
}
["typeMap"]=>
array(3) {
["array"]=>
string(23) "MongoDB\Model\BSONArray"
["document"]=>
string(26) "MongoDB\Model\BSONDocument"
["root"]=>
string(26) "MongoDB\Model\BSONDocument"
}
["writeConcern"]=>
object(MongoDB\Driver\WriteConcern)#7 (4) {
["w"]=>
NULL
["wmajority"]=>
bool(false)
["wtimeout"]=>
int(0)
["journal"]=>
NULL
}
}
.. seealso::
- :phpmethod:`MongoDB\\Collection::__construct`
- :phpmethod:`MongoDB\\Database::__get`
================================
MongoDB\\Database::withOptions()
================================
.. default-domain:: mongodb
Definition
----------
.. phpmethod:: MongoDB\\Database::withOptions
Returns a clone of the Database object, but with different options.
.. code-block:: php
function withOptions(array $options = []): MongoDB\Database
:phpmethod:`MongoDB\\Database::withOptions` supports the
following parameter:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-param.rst
The ``$options`` parameter supports the following options:
.. include:: /includes/apiargs/MongoDBCollection-method-withOptions-option.rst
Example
-------
The following example clones the ``$newDb`` Database object with read
preference ``RP_SECONDARY``.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$newDb = $database->withOptions('sample','restaurants');
$newCollection = $sourceCollection->withOptions([
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]);
.. seealso::
- :phpmethod:`MongoDB\\Collection::__construct`
================================
MongoDB\\Database::__construct()
================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::__construct
Constructs a new :phpclass:`Database <MongoDB\\Database>` instance.
.. code-block:: php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, array $options = [])
:phpmethod:`MongoDB\\Database::__construct` has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-construct-param.rst
:phpmethod:`MongoDB\\Database::__construct` supports the following
options:
.. include:: /includes/apiargs/MongoDBDatabase-method-construct-option.rst
If you construct the Database explicitly, the Database inherits any
options from the ``Manager`` object. If you select the Database
from a :phpclass:`Client <MongoDB\\Client>` object, the Database
inherits its options from that object.
.. seealso::
- :phpmethod:`MongoDB\\Database::withOptions`
==========================
MongoDB\\Database::__get()
==========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. phpmethod:: MongoDB\\Database::__get($collectionName)
Select a collection from the database.
.. code-block:: php
function __get($collectionName): MongoDB\Collection
:phpmethod:`MongoDB\\Database::__get` has the following parameters:
.. include:: /includes/apiargs/MongoDBDatabase-method-get-param.rst
Behavior
--------
The selected database inherits options such as read preference and
type mapping from the :phpclass:`Database <MongoDB\\Database>` object.
If you wish to override any options, use the
:phpmethod:`MongoDB\\Database::selectCollection` method.
.. note::
To select collections whose names contain special characters, such as
``.``, use complex syntax, as in ``$database->{'that.database'}``.
Alternatively, :phpmethod:`MongoDB\\Database::selectCollection` supports
selecting databases whose names contain special characters.
Examples
--------
The following example selects the ``users`` and ``system.profile``
collections from the ``demo`` database:
.. code-block:: php
<?php
$db = (new MongoDB\Client)->demo;
$users = $db->users;
$systemProfile = $db->{'system.profile'};
.. seealso::
- :phpmethod:`MongoDB\\Database::selectCollection`
- :php:`Property Overloading <oop5.overloading>` in the PHP Manual.
Tutorials
=========
.. default-domain:: mongodb
.. toctree::
/tutorial/crud
/tutorial/commands
/tutorial/indexes
# 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)
}
}
```
=========================
Execute Database Commands
=========================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
The |php-library| provides :ref:`helper methods <database-methods>`
for common :manual:`database commands </reference/command>`. In
addition, the |php-library| provides the
:phpmethod:`MongoDB\\Database::command` method to run database commands
with PHP that do not have helper methods.
Execute Database Commands
-------------------------
Basic Command
~~~~~~~~~~~~~
To execute a command on a :program:`mongod` instance, use the
:phpmethod:`MongoDB\\Database::command` method. For instance, the
following operation uses the :dbcommand:`geoNear` HERE command to search for
the three closest documents to longitude ``-74`` and latitude ``40`` in
the ``restos`` collection in the ``example`` database:
:readmode:`secondary`
.. code-block:: php
<?php
$database = (new MongoDB\Client)->example;
$results = $database->command(
[
'geoNear' => 'restos',
'near' => [
'type' => 'Point',
'coordinates' => [-74.0, 40.0]
],
'spherical' => 'true',
'num' => 3
]
);
var_dump($results);
The output would resemble::
object(MongoDB\Driver\Cursor)#10 (2) {
["cursor"]=>
array(17) {
["stamp"]=>
int(0)
["is_command"]=>
bool(true)
["sent"]=>
bool(true)
["done"]=>
bool(false)
["end_of_event"]=>
bool(false)
["in_exhaust"]=>
bool(false)
["has_fields"]=>
bool(false)
["query"]=>
object(stdClass)#3 (4) {
["geoNear"]=>
string(6) "restos"
["near"]=>
object(stdClass)#9 (2) {
["type"]=>
string(5) "Point"
["coordinates"]=>
array(2) {
[0]=>
float(-74)
[1]=>
float(40)
}
}
["spherical"]=>
string(4) "true"
["num"]=>
int(3)
}
["fields"]=>
object(stdClass)#8 (0) {
}
["read_preference"]=>
array(2) {
["mode"]=>
int(1)
["tags"]=>
array(0) {
}
}
["flags"]=>
int(0)
["skip"]=>
int(0)
["limit"]=>
int(1)
["count"]=>
int(1)
["batch_size"]=>
int(0)
["ns"]=>
string(12) "example.$cmd"
["current_doc"]=>
object(stdClass)#24 (4) {
["waitedMS"]=>
int(0)
["results"]=>
array(3) {
[0]=>
object(stdClass)#14 (2) {
["dis"]=>
float(66308.6190421)
["obj"]=>
object(stdClass)#13 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd28"
}
["name"]=>
string(21) "XYZ Bagels Restaurant"
["contact"]=>
object(stdClass)#12 (3) {
["phone"]=>
string(12) "435-555-0190"
["email"]=>
string(31) "XYZBagelsRestaurant@example.net"
["location"]=>
array(2) {
[0]=>
float(-74.0707363)
[1]=>
float(40.5932157)
}
}
["stars"]=>
int(4)
["categories"]=>
array(3) {
[0]=>
string(6) "Bagels"
[1]=>
string(10) "Sandwiches"
[2]=>
string(6) "Coffee"
}
}
}
[1]=>
object(stdClass)#18 (2) {
["dis"]=>
float(69014.6014737)
["obj"]=>
object(stdClass)#17 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd39"
}
["name"]=>
string(20) "Green Feast Pizzeria"
["contact"]=>
object(stdClass)#16 (3) {
["phone"]=>
string(12) "840-555-0102"
["email"]=>
string(30) "GreenFeastPizzeria@example.com"
["location"]=>
array(2) {
[0]=>
float(-74.1220973)
[1]=>
float(40.6129407)
}
}
["stars"]=>
int(2)
["categories"]=>
array(2) {
[0]=>
string(5) "Pizza"
[1]=>
string(7) "Italian"
}
}
}
[2]=>
object(stdClass)#22 (2) {
["dis"]=>
float(69975.5031089)
["obj"]=>
object(stdClass)#21 (5) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#19 (1) {
["oid"]=>
string(24) "57506d62f57802807471dd35"
}
["name"]=>
string(14) "XYZ Coffee Bar"
["contact"]=>
object(stdClass)#20 (3) {
["phone"]=>
string(12) "644-555-0193"
["email"]=>
string(24) "XYZCoffeeBar@example.net"
["location"]=>
array(2) {
[0]=>
float(-74.0166091)
[1]=>
float(40.6284767)
}
}
["stars"]=>
int(5)
["categories"]=>
array(4) {
[0]=>
string(6) "Coffee"
[1]=>
string(4) "Cafe"
[2]=>
string(6) "Bakery"
[3]=>
string(10) "Chocolates"
}
}
}
}
["stats"]=>
object(stdClass)#23 (5) {
["nscanned"]=>
int(11)
["objectsLoaded"]=>
int(10)
["avgDistance"]=>
float(68432.9078749)
["maxDistance"]=>
float(69975.5031089)
["time"]=>
int(0)
}
["ok"]=>
float(1)
}
}
["server_id"]=>
int(1)
}
Commands with Custom Read Preference
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some commands, such as :manual:`createUser
</reference/command/createUser/>`, may only be executed on a
:term:`primary` replica set member or a :term:`standalone`.
The command helper methods in the
|php-library|, such as :phpmethod:`MongoDB\\Database::drop`,
know to apply their own :term:`read preference` if necessary. However,
the :phpmethod:`MongoDB\\Database::command` method is a generic method and
defaults to the read preference of the
Database object on which it is invoked. To execute commands that require
specific read preference, specify the read preference in the ``$options``
parameter of the method.
The following example adds a user to the ``demo`` database
and specifies a custom read preference:
.. code-block:: php
<?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 output would then resemble::
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
View Command Results
--------------------
View Single Result Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Database::command()` method returns a
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object.
Many MongoDB commands return their responses as a single document in an
array. To read the command response, you may either iterate on the
cursor and access the first document, or access the first result in the
array, as in the following:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command(['ping' => 1]);
var_dump($cursor->toArray()[0]);
The output would then resemble::
object(MongoDB\Model\BSONDocument)#2 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
Iterate Results from a Cursor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some commands, such as :manual:`listCollections
</reference/command/listCollections/>`,
return their results via an iterable cursor. To view the results,
iterate through the cursor.
The following example lists the collections in the ``demo`` database by
iterating through the cursor returned by the ``listCollections`` command
using a ``foreach`` loop:
.. code-block:: php
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command(['listCollections' => 1]);
foreach ($cursor as $collection) {
echo $collection['name'], "\n";
}
The output would then be a list of the values for the ``name`` key,
for instance::
persons
posts
zips
.. note::
At the *protocol* level, commands that support a cursor
return a single result document with the essential ingredients for
constructing the command cursor (i.e. the cursor's ID, namespace, and
the first batch of results). In the PHP driver implementation, the
:php:`executeCommand() <mongodb-driver-manager.executecommand>`
method detects the single result and constructs the iterable command
cursor, which is returned rather than the base result document.
# 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/)
===============
CRUD Operations
===============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
CRUD operations *create*, *read*, *update*, and *delete* documents. The
|php-library|'s :phpclass:`MongoDB\\Collection` class implements
MongoDB's cross-driver `CRUD specification
<https://github.com/mongodb/specifications/blob/master/source/crud/crud.
rst>`_, providing access to methods for inserting, finding, updating,
and deleting documents in MongoDB.
This document provides a general introduction to inserting, querying,
updating, and deleting documents using the |php-library|. The MongoDB
Manual's :manual:`CRUD Section </crud>` provides a more thorough
introduction to CRUD operations with MongoDB.
Insert Documents
----------------
Insert One Document
~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::insertOne` method inserts a single
document into MongoDB and returns an instance of ``MongoDB\InsertOneResult``,
which you can use to access the IDs of the inserted document.
.. basic insertOne example:
.. include:: /includes/example-insertOne.rst
The output includes the ``insertedId`` property, which contains the
ID of the inserted document.
If you include an ``_id`` value when inserting a document, MongoDB checks
to ensure that the ``_id`` value is unique for the collection. If the
``_id`` value is not unique, the insert operation fails due to a duplicate
key error.
The following example inserts a document while specifying the value for the ``_id``:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->users;
$insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
The output would then resemble::
Inserted 1 document(s)
int(1)
.. seealso:: :phpmethod:`MongoDB\\Collection::insertOne` reference.
Insert Many Documents
~~~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::insertMany` method allows you to
insert multiple documents in one write operation and returns an instance
of ``MongoDB\InsertManyResult``, which you can use to access the
IDs of the inserted documents.
.. this uses the insertMany example from the method reference:
.. include:: /reference/method/MongoDBCollection-insertMany.txt
:start-after: start-crud-include
:end-before: end-crud-include
.. seealso:: :phpmethod:`MongoDB\\Collection::insertMany` reference.
Query Documents
---------------
The |php-library| provides the :phpmethod:`MongoDB\\Collection::findOne`
and :phpmethod:`MongoDB\\Collection:findMany` methods for querying
documents and the :phpmethod:`MongoDB\\Collection:aggregate`
method for performing :manual:`aggregation operations
</core/aggregation-pipeline`.
Find One Document
~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::findOne` returns the :term:`first
document <natural order>` that matches the query or ``null`` if no
document matches the query.
The following example searches for the document with ``_id: 94301``:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$document = $collection->findOne(['_id' => '94301']);
var_dump($document);
The output would then resemble::
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"
}
}
.. seealso:: :phpmethod:`MongoDB\\Collection::findMany` reference
Find Many Documents
~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::find` returns a
:php:`MongoDB\\Driver\\Cursor <mongodb-driver-cursor>` object, which you
can iterate upon to access all matched documents.
The following example lists the documents in the ``zips`` collection
with the specified city and state values:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']);
foreach ($cursor as $document) {
echo $document['_id'], "\n";
}
The output would resemble::
07302
07304
07305
07306
07307
07310
.. seealso:: :phpmethod:`MongoDB\\Collection::find` reference
.. _php-query-projection:
Query Projection
~~~~~~~~~~~~~~~~
By default, queries in MongoDB return all fields in matching documents.
To limit the amount of data that MongoDB sends to applications, you can
include a :manual:`projection document
</tutorial/project-fields-from-query-results>` in the query operation.
.. note::
MongoDB includes the ``_id`` field by default unless you explicitly
exclude it in a projection document.
The following example finds restaurants based on the ``cuisine`` and
``borough`` fields and uses a :manual:`projection
</tutorial/project-fields-from-query-results>` to limit the fields
that are returned. It also limits the results to 5 documents.
.. code-block:: php
<?php
$database = new MongoDB\Client;
$collection = $database->selectCollection('example','restaurants');
$restaurants = $collection->find(
[ 'cuisine' => 'Italian', 'borough' => 'Manhattan'],
[
'projection' => [
'name' => 1, 'borough' => 1, 'cuisine' => 1,
],
]
);
foreach($restaurants as $restaurant) {
var_dump($restaurant);
};
The output would then resemble::
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#8 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f983"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(23) "Isle Of Capri Resturant"
}
}
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#12 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f98d"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(18) "Marchis Restaurant"
}
}
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#10 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f99b"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(19) "Forlinis Restaurant"
}
}
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(4) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#13 (1) {
["oid"]=>
string(24) "576023c6b02fa9281da3f9a8"
}
["borough"]=>
string(9) "Manhattan"
["cuisine"]=>
string(7) "Italian"
["name"]=>
string(22) "Angelo Of Mulberry St."
}
}
...
Limit, Sort, and Skip Options
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In addition to :ref:`projection criteria <php-query-projection>`,
you can specify options to limit, sort, and skip documents during queries.
The following example uses the ``limit`` and ``sort`` options to query
for the five most populous zip codes in the United States:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$cursor = $collection->find(
[],
[
'limit' => 5,
'sort' => ['pop' => -1],
]
);
foreach ($cursor as $document) {
echo $document['_id'], "\n";
}
The output would then resemble::
60623: CHICAGO, IL
11226: BROOKLYN, NY
10021: NEW YORK, NY
10025: NEW YORK, NY
90201: BELL GARDENS, CA
Complex Queries with Aggregation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MongoDB's :manual:`Aggregation Framework </core/aggregation-pipeline>`
allows you to issue complex queries that filter, transform, and group
collection data. The |php-library|\'s
:phpmethod:`MongoDB\\Collection::aggregate` method returns a
:php:`traversable <traversable>` object, which you can iterate upon to
access the results of the aggregation operation. Refer to the
:phpmethod:`MongoDB\\Collection::aggregate` method's :ref:`output
reference <php-agg-method-output>` for more about the method's output.
The following example lists the 5 US states with the most zip codes
associated with them:
.. code-block:: php
<?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 output would then resemble::
TX has 1671 zip codes
NY has 1595 zip codes
CA has 1516 zip codes
PA has 1458 zip codes
IL has 1237 zip codes
.. seealso:: :phpmethod:`MongoDB\\Collection::aggregate` reference
Update Documents
----------------
Update One Document
~~~~~~~~~~~~~~~~~~~
Use the :phpmethod:`MongoDB\\Collection::updateOne` method to update a
single document matching a filter.
:phpmethod:`MongoDB\\Collection::updateOne` returns a
``MongoDB\UpdateResult`` object, which you can use to access statistics
about the update operation.
Update methods have two required parameters: the query filter that
identifies the document or documents to update, and an update document
that specifies what updates to perform. The :phpmethod:`MongoDB\\Collection::updateOne`
reference describes each parameter in detail.
The following example inserts two documents into an empty ``users`` collection
in the ``demo`` database using the :phpmethod:`MongoDB\\Collection::insertOne`
method, and then updates the documents where the value for the ``state``
field is ``"ny"`` to include
a ``country`` field set to ``"us"``:
.. code-block:: php
<?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());
Since the update operation uses the
:phpmethod:`MongoDB\\Collection::updateOne` method, which updates the
first document to match the filter criteria, the results would then
resemble::
Matched 1 document(s)
Modified 1 document(s)
It is possible for a document to match the filter but *not be modified*
by an update, as is the case where the update sets a field's value to its
existing value, as in this example:
.. code-block:: php
<?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 number of matched documents and the number of *modified* documents
would therefore not be equal, and the output from the operation would
resemble::
Matched 1 document(s)
Modified 0 document(s)
.. seealso::
- :phpmethod:`MongoDB\\Collection::updateOne` reference
- :phpmethod:`MongoDB\\Collection::findOneAndUpdate` reference
Update Many Documents
~~~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::updateMany` updates one or more documents
matching the filter criteria and returns a ``MongoDB\UpdateResult`` object
that you can iterate to access statistics about the update operation.
Update methods have two required parameters: the query filter that
identifies the document or documents to update, and an update document
that specifies what updates to perform. The :phpmethod:`MongoDB\\Collection::updateMany`
reference describes each parameter in detail.
The following example inserts three documents into an empty ``users``
collection in the ``demo`` database and then uses the :query:`$set`
operator to update the documents matching the filter criteria to
include the ``country`` field with value ``"us"``:
.. code-block:: php
<?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());
If an update operation results in no change to a document, such as
setting the value of the field to its current value, the number of
modified documents can be less than the number of *matched* documents.
Since the update document with ``name`` of ``"Bob"`` results in no changes
to the document, the output of the operation therefore resembles::
Matched 3 document(s)
Modified 2 document(s)
.. seealso:: :phpmethod:`MongoDB\\Collection::updateMany` reference
Replace Documents
~~~~~~~~~~~~~~~~~
Replacement operations are similar to update operations, but instead
of updating a document to include new fields or new field values, a
replacement operation replaces the entire document with a new document,
but retains the original document's ``_id`` value.
The :phpmethod:`MongoDB\\Collection::replaceOne` method replaces a single
document that matches the filter criteria and returns
an instance of ``MongoDB\UpdateResult`` that
you can use to access statistics about the replacement operation.
:phpmethod:`MongoDB\\Collection::replaceOne` has two required
parameters: the query filter that identifies the document or documents
to update, and a replacement document that will replace the original
document in MongoDB. The :phpmethod:`MongoDB\\Collection::replaceOne`
reference describes each parameter in detail.
.. important::
Replacement operations replace all of the fields in a document
except the ``_id`` value. To avoid accidentally overwriting or
deleting desired fields, use the
:phpmethod:`MongoDB\\Collection::updateOne` or
:phpmethod:`MongoDB\\Collection::updateMany` methods to update
individual fields in a document rather than replacing the entire
document.
The following example inserts one document into an empty ``users`` collection
in the ``demo`` database, and then replaces that document with a new one:
.. code-block:: php
<?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 output would then resemble::
Matched 1 document(s)
Modified 1 document(s)
.. seealso::
- :phpmethod:`MongoDB\\Collection::replaceOne` reference
- :phpmethod:`MongoDB\\Collection::findOneAndReplace` reference
Upsert
~~~~~~
Update and replace operations support an :manual:`upsert
</tutorial/update-documents/#upsert-option>` option. When ``upsert`` is
``true`` *and* no documents match the specified filter, then the
operation creates a new document and inserts it. If there *are* matching
documents, then the operation modifies or replaces the matching
document or documents.
When a document is upserted, the ID is accessible via
``MongoDB\UpdateResult::getUpsertedId()``.
The following example uses :phpmethod:`MongoDB\\Collection::updateOne`
with the ``upsert`` option set to ``true`` into an empty ``users``
collection in the ``demo`` database, therefore inserting the document
into the database:
.. code-block:: php
<?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 output would then resemble::
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"
}
}
Delete Documents
----------------
Delete One Document
~~~~~~~~~~~~~~~~~~~
The :phpmethod:`MongoDB\\Collection::deleteOne` method deletes a single
document that matches the filter criteria and returns a
``MongoDB\DeleteResult`` object that you can use to access statistics
about the delete operation. If multiple documents match the filter
criteria, :phpmethod:`MongoDB\\Collection::deleteOne` deletes the
:term:`first <natural order>` matching document.
:phpmethod:`MongoDB\\Collection::deleteOne` has one required parameter:
a query filter that specifies the document to delete. Refer to the
:phpmethod:`MongoDB\\Collection::deleteOne` reference for full method documentation.
The following operation deletes the first document where the ``state``
value is ``ny``:
.. code-block:: php
<?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 output would then resemble::
Deleted 1 document(s)
.. seealso:: :phpmethod:`MongoDB\\Collection::deleteOne` reference.
Delete Many Documents
~~~~~~~~~~~~~~~~~~~~~
:phpmethod:`MongoDB\\Collection::deleteMany` deletes all of the
documents that match the filter criteria and returns a
``MongodB\DeleteResult`` object that you can use to access statistics
about the delete op eration.
:phpmethod:`MongoDB\\Collection::deleteMany` has one required
parameter: a query filter that specifies the document to delete. Refer
to the :phpmethod:`MongoDB\\Collection::deleteMany` reference for full
method documentation.
The following operation deletes all of the documents where the
``state`` field has value ``"ny"``:
.. code-block:: php
<?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 output would then resemble::
Deleted 2 document(s)
.. seealso:: :phpmethod:`MongoDB\\Collection::deleteMany` reference
# 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)
}
}
```
=======
Indexes
=======
.. default-domain:: mongodb
Indexes support the efficient execution of queries in MongoDB. Without
indexes, MongoDB must perform a *collection scan*, i.e. scan every
document in a collection, to select those documents that match the
query statement. If an appropriate index exists for a query,
MongoDB can use the index to limit the number of documents it must
inspect.
The PHP driver supports managing indexes through the
:phpclass:`MongoDB\\Collection` class, which implements MongoDB's
cross-driver `Index Management
<https://github.com/mongodb/specifications/blob/master/source/index-management.rst>`_
and `Enumerating Indexes
<https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst>`_
specifications.
This document provides an introduction to creating, listing, and
dropping indexes using the |php-library|. The MongoDB Manual's
:manual:`Indexes Section </indexes>` provides more thorough
information about indexing in MongoDB.
Create Indexes
--------------
Create indexes with the :phpmethod:`MongoDB\\Collection::createIndex`
and :phpmethod:`MongoDB\\Collection::createIndexes` methods. Refer to
the method reference for more details about each method.
The following example creates an ascending index on the ``state`` field
using the :phpmethod:`createIndex` method:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->createIndex(['state' => 1]);
var_dump($result);
When you create an index, the method returns its name, which is
automatically generated from its specification. The above example would
output something similar to::
string(7) "state_1"
List Indexes
------------
The :phpmethod:`MongoDB\\Collection::listIndexes` method provides
information about the indexes in a collection.
:phpmethod:`MongoDB\\Collection::listIndexes` method returns an
iterator of ``MongoDB\Model\IndexInfo`` objects, which you can use to
view information about each index. Refer to the method reference for
more details about each method.
The following example lists all indexes in the ``zips`` collection in
the ``demo`` database:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
foreach ($collection->listIndexes() as $indexInfo) {
var_dump($indexInfo);
}
The output would resemble::
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"
}
Drop Indexes
------------
The :phpmethod:`MongoDB\\Collection::dropIndex` lets you drop a single index while
:phpmethod:`MongoDB\\Collection::dropIndexes` drops all of the indexes on a collection.
Refer to the method reference for more details about each method.
The following example drops a single index by its name, ``state_1``:
.. code-block:: php
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->dropIndex('state_1');
var_dump($result);
The operation's output would resemble::
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
=========================
Install the |php-library|
=========================
.. default-domain:: mongodb
Prerequisites
-------------
The MongoDB PHP Library is a high-level abstraction for the
MongoDB PHP driver. As such, you must install the `mongodb`
extension to use the |php-library|:
.. code-block:: sh
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 :php:`Installation with HHVM
<mongodb.installation.hhvm>` article
in the driver documentation.
Procedure
---------
Install the Library
~~~~~~~~~~~~~~~~~~~
The preferred method of installing |php-library| is with `Composer
<https://getcomposer.org/>`_ by running the following from your project
root:
.. code-block:: sh
composer require "mongodb/mongodb=^1.0.0"
While not recommended, you may also manually install the package via
the source tarballs attached to the `GitHub releases
<https://github.com/mongodb/mongo-php-library/releases>`_.
Configure Autoloading
~~~~~~~~~~~~~~~~~~~~~
Once you have installed the library, ensure that your application
includes Composer's autoloader. The ``require_once``
statement should point to Composer's autoloader, as in the following example:
.. code-block:: php
require_once __DIR__ . "/vendor/autoload.php";
Refer to Composer's `autoloading documentation
<https://getcomposer.org/doc/01-basic-usage.md#autoloading>`_ for more
information about setting up autoloading.
If you installed the library manually from a source tarball, you
will also need to manually configure autoloading:
#. 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.
# 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
=============
Upgrade Guide
=============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
The MongoDB PHP Library and underlying :php:`mongodb
extension <mongodb>` have notable API differences from
the legacy :php:`mongo extension <mongo>`. This page will
summarize those differences for the benefit of those
upgrading from the legacy driver.
Additionally, a community-developed
`mongo-php-adapter <https://github.com/alcaeus/mongo-php-adapter>`__
library exists, which implements the `mongo
extension <http://php.net/mongo>`__ API using this library and the new
driver. While this adapter library is not officially supported by
MongoDB, it does bear mentioning.
Collection API
~~~~~~~~~~~~~~
This library's :phpclass:`MongoDB\\Collection` class
implements MongoDB's cross-driver
`CRUD <https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst>`__
and `Index
Management <https://github.com/mongodb/specifications/blob/master/source/index-management.rst>`__
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 <http://php.net/mongocollection>`__ class with some
notable exceptions.
Old and New Methods
~~~~~~~~~~~~~~~~~~~
.. list-table::
:header-rows: 1
* - :php:`MongoCollection <class.mongocollection>`
- :phpclass:`MongoDB\\Collection`
* - :php:`MongoCollection::aggregate() <mongocollection.aggregate>`
- :phpmethod:`MongoDB\\Collection::aggregate`
* - :php:`MongoCollection::aggregateCursor() <mongocollection.aggregatecursor>`
- :phpmethod:`MongoDB\\Collection::aggregate`
* - :php:`MongoCollection::batchInsert() <mongocollection.batchinsert>`
- :phpmethod:`MongoDB\\Collection::insertMany`
* - :php:`MongoCollection::count() <mongocollection.count>`
- :phpmethod:`MongoDB\\Collection::count`
* - :php:`MongoCollection::createDBRef() <mongocollection.createdbref>`
- Not yet implemented. See :issue:`PHPLIB-24`
* - :php:`MongoCollection::createIndex() <mongocollection.createindex>`
- :phpmethod:`MongoDB\\Collection::createIndex`
* - :php:`MongoCollection::deleteIndex() <mongocollection.deleteindex>`
- :phpmethod:`MongoDB\\Collection::dropIndex`
* - :php:`MongoCollection::deleteIndexes() <mongocollection.deleteindexes>`
- :phpmethod:`MongoDB\\Collection::dropIndexes`
* - :php:`MongoCollection::drop() <mongocollection.drop>`
- :phpmethod:`MongoDB\\Collection::drop`
* - :php:`MongoCollection::distinct() <mongocollection.distinct>`
- :phpmethod:`MongoDB\\Collection::distinct`
* - :php:`MongoCollection::ensureIndex() <mongocollection.ensureindex>`
- :phpmethod:`MongoDB\\Collection::createIndex`
* - :php:`MongoCollection::find() <mongocollection.find>`
- :phpmethod:`MongoDB\\Collection::find`
* - :php:`MongoCollection::findAndModify() <mongocollection.findandmodify>`
- :phpmethod:`MongoDB\\Collection::findOneAndDelete`,
:phpmethod:`MongoDB\\Collection::findOneAndReplace`, and
:phpmethod:`MongoDB\\Collection::findOneAndUpdate()`
* - :php:`MongoCollection::findOne() <mongocollection.findone>`
- :phpmethod:`MongoDB\\Collection::findOne`
* - :php:`MongoCollection::getDBRef() <mongocollection.getdbref>`
- Not implemented. See :issue:`PHPLIB-24`
* - :php:`MongoCollection::getIndexInfo() <mongocollection.getindexinfo>`
- :phpmethod:`MongoDB\\Collection::listIndexes`
* - :php:`MongoCollection::getName() <mongocollection.getname>`
- :phpmethod:`MongoDB\\Collection::getCollectionName`
* - :php:`MongoCollection::getReadPreference() <mongocollection.getreadpreference>`
- Not implemented.
* - :php:`MongoCollection::getSlaveOkay() <mongocollection.getslaveokay>`
- Not implemented.
* - :php:`MongoCollection::getWriteConcern() <mongocollection.getwriteconcern>`
- Not implemented.
* - :php:`MongoCollection::group() <mongocollection.group>`
- Not yet implemented. See :issue:`PHPLIB-177`.
Use :phpmethod:`MongoDB\\Database::command`.
* - :php:`MongoCollection::insert() <mongocollection.insert>`
- :phpmethod:`MongoDB\\Collection::insertOne`
* - :php:`MongoCollection::parallelCollectionScan() <mongocollection.parallelcollectionscan>`
- Not implemented.
* - :php:`MongoCollection::remove() <mongocollection.remove>`
- :phpmethod:`MongoDB\\Collection::deleteMany` and
:phpmethod:`MongoDB\\Collection::deleteOne`
* - :php:`MongoCollection::save() <mongocollection.save>`
- :phpmethod:`MongoDB\\Collection::insertOne` or
:phpmethod:`MongoDB\\Collection::replaceOne` with the ``upsert``
option.
* - :php:`MongoCollection::setReadPreference() <mongocollection.setreadpreference>`
- Not implemented. Use :phpmethod:`MongoDB\\Collection::withOptions()`
* - :php:`MongoCollection::setSlaveOkay() <mongocollection.getslaveokay>`
- Not implemented.
* - :php:`MongoCollection::setWriteConcern() <mongocollection.setwriteconcern>`
- Not implemented. Use :phpmethod:`MongoDB\\Collection::withOptions`
* - :php:`MongoCollection::update() <mongocollection.update>`
- :phpmethod:`MongoDB\\Collection::replaceOne`,
:phpmethod:`MongoDB\\Collection::updateMany`, and
:phpmethod:`MongoDB\\Collection::updateOne`.
* - :php:`MongoCollection::validate() <mongocollection.validate>`
- Not implemented.
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, :php:`MongoCollection::save() <mongocollection.save>` and
:php:`MongoCollection::findAndModify() <mongocollection.findandmodify>`
have different modes of operation, depending on their arguments.
Methods were also split to distinguish between :manual:`updating
specific fields </tutorial/modify-documents>` and :manual:`full-document
replacement </tutorial/modify-documents/#replace-the-document>`.
Group Command Helper
~~~~~~~~~~~~~~~~~~~~
:phpclass:`MongoDB\\Collection` does not
yet have a helper method for the :manual:`group
</reference/command/group>` command; however, it is planned in
:issue:`PHPLIB-177`. The following example demonstrates how to execute
a group command using the :phpmethod:`MongoDB\\Database::command()` method:
.. code-block:: 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];
MapReduce Command Helper
~~~~~~~~~~~~~~~~~~~~~~~~
:phpclass:`MongoDB\\Collection` does not yet have a helper method for
the :manual:`mapReduce </reference/command/mapReduce/>` command;
however, that is planned in :issue:`PHPLIB-53`. The following example
demonstrates how to execute a mapReduce command using the
:phpmethod:`MongoDB\\Database::command()` method:
.. code-block:: 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];
?>
DBRef Helpers
~~~~~~~~~~~~~
:phpclass:`MongoDB\\Collection` does not yet
have helper methods for working with
:manual:`DBRef </reference/database-references>`
objects; however, that is planned in
:issue:`PHPLIB-24`.
MongoCollection::save() Removed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:php:`MongoCollection::save() <mongocollection.save>`,
which was syntactic sugar for an insert or upsert operation, has been
removed in favor of explicitly using
:phpmethod:`MongoDB\\Collection::insertOne` or
:phpmethod:`MongoDB\\Collection::replaceOne` with the ``upsert``
option).
.. .. figure:: img/save-flowchart.png
.. :alt: save() flowchart
While the ``save``
method does have its uses for interactive environments, such as the
mongo shell, it was intentionally excluded from the
`CRUD <https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst>`_
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 :manual:`full-document
replacements </tutorial/modify-documents>`.
Accessing IDs of Inserted Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the legacy driver, :php:`MongoCollection::insert()
<mongocollection.insert>`, :php:`MongoCollection::batchInsert()
<mongocollection.batchinsert`, and :php:`MongoCollection::save()
<mongocollection.save>` (when inserting) would modify their input
argument by injecting an ``_id`` key containing the generated ObjectId
(i.e. :php:`MongoId <class.mongoid>` object). This behavior was a bit
of a hack, as it did not rely on the argument being :php:`passed by
reference <language.references.pass>`; instead, 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.
IDs of inserted documents (whether generated or not) may be accessed
through the result objects returned by the write methods:
- ``MongoDB\InsertOneResult::getInsertedId()`` for
:phpmethod:`MongoDB\\Collection::insertOne`
- ``MongoDB\InsertManyResult::getInsertedIds()`` for
:phpmethod:`MongoDB\\Collection::insertMany`
- ``MongoDB\BulkWriteResult::getInsertedIds()`` for
:phpmethod:`MongoDB\\Collection::bulkWrite`
``MongoWriteBatch``
~~~~~~~~~~~~~~~~~~~
The legacy driver's
:php:`MongoWriteBatch <class.mongowritebatch>`
classes have been replaced with a general-purpose
:phpmethod:`MongoDB\\Collection::bulkWrite` method. Whereas the
legacy driver only allowed bulk operations of the same type, the new
method allows operations to be mixed (e.g. inserts, updates, and
deletes).
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