Commit e2c4a0c5 authored by Jeremy Mikola's avatar Jeremy Mikola

Split Collection docs into API, tutorial, and upgrade guide

parent 84510286
# MongoDB\Collection
`MongoDB\Collection` is perhaps the most useful class in this library. It
provides methods for common operations on a collection, such as inserting
documents, querying, updating, counting, etc.
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)
or selected from the library's Client class. It supports the following options:
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)
If any options are omitted, they will be inherited from the Manager constructor
argument or object from which the Collection was selected.
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.
Operations within the Collection class (e.g. `find()`, `insertOne()`) will
generally inherit the Collection's options. One notable exception to this rule
is that `aggregate()` (when not using a cursor) and the `findAndModify` variants
do not yet support a type map option due to a driver limitation. This means that
they will return BSON documents and arrays as `stdClass` objects and PHP arrays,
respectively.
[findandmodify]: http://docs.mongodb.org/manual/reference/command/findAndModify/
## Collection-level Operations
---
The Collection class has methods for collection-level operations, such as
dropping the collection, CRUD operations, or managing the collection's indexes.
## __construct()
### Dropping the Collection
```php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, $collectionName, array $options = [])
```
If the Collection is constructed explicitly, any omitted options will be
inherited from the Manager object. If the Collection is selected from a
[Client](client.md) or [Database](database.md) object, options will be
inherited from that object.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for collection operations. Defaults to the
Manager's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for collection operations. Defaults to
the Manager's read preference.
typeMap (array)
: Default type map for cursors and BSON documents.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for collection operations. Defaults to the
Manager's write concern.
### See Also
* [MongoDB\Collection::withOptions()](#withoptions)
---
## 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 custom type map. Support is pending new
functionality in the driver.
### 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/)
---
## 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);
```
......@@ -52,161 +409,548 @@ object(MongoDB\Model\BSONDocument)#11 (1) {
}
```
## CRUD Operations
### See Also
CRUD is an acronym for Create, Read, Update, and Delete. The Collection class
implements MongoDB's cross-driver
[CRUD specification](https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst),
which defines a common API for collection-level read and write methods.
* [MongoDB Manual: drop command](https://docs.mongodb.org/manual/reference/command/drop/)
Each method on the Collection class corresponds to a particular Operation class
within the library. The Collection's method merely merges in relevant options
(e.g. read preferences, type maps). Documentation for each CRUD method and its
options may be found in either the CRUD specification or those Operation
classes.
---
### API Differences from the Legacy Driver
## dropIndex()
The CRUD API has some notable differences from the legacy driver's
[MongoCollection](http://php.net/mongocollection) class:
```php
function dropIndex($indexName, array $options = []): array|object
```
Drop a single index in the collection. Returns the command result document.
### Supported Options
* `insert()` and `batchInsert()` have been renamed to `insertOne()` and
`insertMany()`, respectively.
* `update()` has been split into `updateOne()`, `updateMany()`, and
`replaceOne()`.
* `remove()` has been split into `deleteOne()` and `deleteMany()`.
* `findAndModify()` has been split into `findOneAndDelete()`,
`findOneAndReplace()`, and `findOneAndUpdate()`.
* `save()`, which was syntactic sugar for an insert or upsert operation, has
been removed in favor of explicitly using `insertOne()` or `replaceOne()`
(with the `upsert` option).
* `aggregate()` and `aggregateCursor()` have been consolidated into a single
`aggregate()` method.
* A general-purpose `bulkWrite()` method replaces the legacy driver's
[`MongoWriteBatch`](http://php.net/mongowritebatch) class.
typeMap (array)
: Type map for BSON deserialization. This will be used for the returned
command result document.
The general rule in designing our new API was that explicit method names were
preferable to overloaded terms found in the old API. For instance, `save()` and
`findAndModify()` had two or three very different modes of operation, depending
on their arguments. These new methods names also distinguish between
[updating specific fields](https://docs.mongodb.org/manual/tutorial/modify-documents/#update-specific-fields-in-a-document)
and [full-document replacement](https://docs.mongodb.org/manual/tutorial/modify-documents/#replace-the-document).
### See Also
### Finding One or More Document(s)
* [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]
The `findOne()` and `find()` methods may be used to query for one or multiple
documents.
---
## dropIndexes()
```php
function dropIndexes(array $options = []): array|object
```
$collection = (new MongoDB\Client)->demo->zips;
$document = $collection->findOne(['_id' => '94301']);
var_dump($document);
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
```
The above example would output something similar to:
Finds documents matching the query. Returns a MongoDB\Driver\Cursor.
### Supported Options
allowPartialResults (boolean)
: Get partial results from a mongos if some shards are inaccessible (instead
of throwing an error).
batchSize (integer)
: The number of documents to return per batch.
comment (string)
: Attaches a comment to the query. If "$comment" also exists in the modifiers
document, this option will take precedence.
cursorType (enum)
: Indicates the type of cursor to use. Must be either NON_TAILABLE, TAILABLE,
or TAILABLE_AWAIT. The default is NON_TAILABLE.
limit (integer)
: The maximum number of documents to return.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run. If "$maxTimeMS" also
exists in the modifiers document, this option will take precedence.
modifiers (document)
: Meta-operators modifying the output or behavior of a query.
noCursorTimeout (boolean)
: The server normally times out idle cursors after an inactivity period (10
minutes) to prevent excess memory use. Set this option to prevent that.
oplogReplay (boolean)
: Internal replication use only. The driver should not set this.
projection (document)
: Limits the fields to return for the matching document.
readConcern (MongoDB\Driver\ReadConcern)
: Read concern.
<br><br>
For servers < 3.2, this option is ignored as read concern is not
available.
readPreference (MongoDB\Driver\ReadPreference)
: Read preference.
skip (integer)
: The number of documents to skip before returning.
sort (document)
: The order in which to return matching documents. If "$orderby" also exists
in the modifiers document, this option will take precedence.
typeMap (array)
: Type map for BSON deserialization. This will be applied to the returned
Cursor (it is not sent to the server).
### See Also
* [MongoDB\Collection::findOne()](#findOne)
* [MongoDB Manual: find command](http://docs.mongodb.org/manual/reference/command/find/)
---
## findOne()
```php
function findOne($filter = [], array $options = []): array|object
```
object(MongoDB\Model\BSONDocument)#13 (1) {
["storage":"ArrayObject":private]=>
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"
}
}
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
```
The `find()` method returns a
[`MongoDB\Driver\Cursor`](http://php.net/mongodb-driver-cursor) object, which
may be iterated upon to access all matched documents.
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
custom type map. Support is pending new functionality in the driver.
### Supported Options
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
## Index Management
projection (document)
: Limits the fields to return for the matching document.
The Collection class 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, which defines a common API for index-related methods.
sort (document)
: Determines which document the operation modifies if the query selects
multiple documents.
### Creating Indexes
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern. This option is only supported for server versions >= 3.2.
### See Also
* [MongoDB\Collection::findOneAndReplace()](#findoneandreplace)
* [MongoDB\Collection::findOneAndUpdate()](#findoneandupdate)
* [MongoDB Manual: findAndModify command][findandmodify]
---
## findOneAndReplace()
```php
function findOneAndReplace($filter, $replacement, array $options = []): object|null
```
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->createIndex(['state' => 1]);
var_dump($result);
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
custom type map. Support is pending new functionality in the driver.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
projection (document)
: Limits the fields to return for the matching document.
returnDocument (enum)
: Whether to return the document before or after the update is applied. Must
be either `MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE` or
`MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_AFTER`. The default is
`MongoDB\Operation\FindOneAndReplace::RETURN_DOCUMENT_BEFORE`.
sort (document)
: Determines which document the operation modifies if the query selects
multiple documents.
upsert (boolean)
: When true, a new document is created if no document matches the query. The
default is false.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern. This option is only supported for server versions >= 3.2.
### See Also
* [MongoDB\Collection::findOneAndDelete()](#findoneanddelete)
* [MongoDB\Collection::findOneAndUpdate()](#findoneandupdate)
* [MongoDB Manual: findAndModify command][findandmodify]
---
## findOneAndUpdate()
```php
function findOneAndUpdate($filter, $update, array $options = []): object|null
```
The above example would output something similar to:
Finds a single document and updates it, returning either the original or the
updated document.
The document to return may be null if no document matched the filter. By
default, the original document is returned. Specify
`MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER` for the
"returnDocument" option to return the updated document.
**Note:** BSON deserialization of the returned document does not yet support a
custom type map. Support is pending new functionality in the driver.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
projection (document)
: Limits the fields to return for the matching document.
returnDocument (enum)
: Whether to return the document before or after the update is applied. Must
be either `MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_BEFORE` or
`MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER`. The default is
`MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_BEFORE`.
sort (document)
: Determines which document the operation modifies if the query selects
multiple documents.
upsert (boolean)
: When true, a new document is created if no document matches the query. The
default is false.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern. This option is only supported for server versions >= 3.2.
### See Also
* [MongoDB\Collection::findOneAndDelete()](#findoneanddelete)
* [MongoDB\Collection::findOneAndReplace()](#findoneandreplace)
* [MongoDB Manual: findAndModify command][findandmodify]
---
## getCollectionName()
```php
function getCollectionName(): string
```
string(7) "state_1"
Return the collection name.
---
## getDatabaseName()
```php
function getDatabaseName(): string
```
### Dropping Indexes
Return the database name.
---
## getNamespace()
```php
function getNamespace(): string
```
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->dropIndex('state_1');
var_dump($result);
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
```
The above example would output something similar to:
Inserts multiple documents.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
ordered (boolean)
: If true, when an insert fails, return without performing the remaining
writes. If false, when a write fails, continue with the remaining writes, if
any. The default is true.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::insertOne()](#insertone)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: insert command](http://docs.mongodb.org/manual/reference/command/insert/)
---
## insertOne()
```php
function insertOne($document, array $options = []): MongoDB\InsertOneResult
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
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
```
### Enumerating Indexes
Returns information for all indexes for the collection. Elements in the returned
iterator will be MongoDB\Model\IndexInfo objects.
### Supported Options
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
### See Also
* [Tutorial: Indexes](../tutorial/indexes.md)
* [MongoDB Manual: listIndexes command](http://docs.mongodb.org/manual/reference/command/listIndexes/)
* [MongoDB Manual: Indexes][indexes]
* [MongoDB Specification: Enumerating Collections](https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst)
---
## replaceOne()
```php
function replaceOne($filter, $replacement, array $options = []): MongoDB\UpdateResult
```
/* listIndexes() returns an iterator of MongoDB\Model\IndexInfo objects */
$collection = (new MongoDB\Client)->demo->zips;
foreach ($collection->listIndexes() as $indexInfo) {
var_dump($indexInfo);
}
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
```
The above example would output something similar to:
Updates all documents matching the filter.
### Supported Options
bypassDocumentValidation (boolean)
: If true, allows the write to opt out of document level validation.
upsert (boolean)
: When true, a new document is created if no document matches the query. The
default is false.
writeConcern (MongoDB\Driver\WriteConcern)
: Write concern.
### See Also
* [MongoDB\Collection::bulkWrite()](#bulkwrite)
* [MongoDB\Collection::replaceOne()](#replaceone)
* [MongoDB\Collection::updateOne()](#updateone)
* [Tutorial: CRUD Operations](../tutorial/crud.md)
* [MongoDB Manual: update command](http://docs.mongodb.org/manual/reference/command/update/)
---
## updateOne()
```php
function updateOne($filter, $update, array $options = []): MongoDB\UpdateResult
```
object(MongoDB\Model\IndexInfo)#4 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["_id"]=>
int(1)
}
["name"]=>
string(4) "_id_"
["ns"]=>
string(9) "demo.zips"
}
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)
# 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/
## Querying
### Finding One Document
The [findOne()][findone] method returns the first matched document, or null if
no document was matched. 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.
[findone]: ../classes/collection.md#findone
[arrayobject]: http://php.net/arrayobject
[serializable]: http://php.net/mongodb-bson-serializable
[unserializable]: http://php.net/mongodb-bson-unserializable
```
<?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"
}
}
```
Most methods that read data from MongoDB support a "typeMap" option, which
allows control over how BSON is converted to PHP. If desired, this option can be
used to return everything as a PHP array, as was done in the legacy
[mongo extension][ext-mongo]:
[ext-mongo]: http://php.net/mongo
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$document = $collection->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"
}
```
### Finding Many Documents
The [find()][find] method returns a [MongoDB\Driver\Cursor][cursor] object,
which may be iterated upon to access all matched documents.
[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
```
# Example Data
Some examples in this documentation use example data fixtures from
[zips.json](http://media.mongodb.org/zips.json). This is a dataset comprised of
United States postal codes, populations, and geographic locations.
[zips.json][zips]. This is a dataset comprised of United States postal codes,
populations, and geographic locations.
Importing the dataset into MongoDB can be done in several ways. The following
example uses [PHP driver](http://php.net/mongodb) (i.e. `mongodb` extension).
example uses [mongodb extension][ext-mongodb]:
[zips]: http://media.mongodb.org/zips.json
[ext-mongodb]: http://php.net/mongodb
```
<?php
$file = 'http://media.mongodb.org/zips.json';
$zips = file($file, FILE_IGNORE_NEW_LINES);
......@@ -30,10 +35,11 @@ Executing this script should yield the following output:
Inserted 29353 documents
```
You may also import the dataset using the
[`mongoimport`](http://docs.mongodb.org/manual/reference/program/mongoimport/)
command, which is included with MongoDB:
You may also import the dataset using the [mongoimport][mongoimport] command,
which is included with MongoDB:
```
[mongoimport]: http://docs.mongodb.org/manual/reference/program/mongoimport/
```bash
$ mongoimport --db demo --collection zips --file zips.json --drop
```
# Indexes
Indexes may be managed via the [MongoDB\Collection][collection] class, which
implements MongoDB's cross-driver [Index Management][index-spec] and
[Enumerating Indexes][enum-spec] specifications. This page will demonstrate how
to create, list, and drop indexes using the library. General information on how
indexes work in MongoDB may be found in the [MongoDB manual][indexes].
[collection]: ../classes/collection.md
[index-spec]: https://github.com/mongodb/specifications/blob/master/source/index-management.rst
[enum-spec]: https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst
[indexes]: https://docs.mongodb.org/manual/indexes/
## Creating Indexes
Indexes may be created via the [createIndex()][createindex] and
[createIndexes()][createindexes] methods. The following example creates an
ascending index on the "state" field:
[createindex]: ../classes/collection.md#createindex
[createindexes]: ../classes/collection.md#createindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->createIndex(['state' => 1]);
var_dump($result);
```
Creating an index will return its name, which is automatically generated from
its specification (i.e. fields and orderings). The above example would output
something similar to:
```
string(7) "state_1"
```
### Enumerating Indexes
Information about indexes in a collection may be obtained via the
[listIndexes()][listindexes] method, which returns an iterator of
MongoDB\Model\IndexInfo objects. The following example lists all indexes in the
"demo.zips" collection:
[listindexes]: ../classes/collection.md#listindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
foreach ($collection->listIndexes() as $indexInfo) {
var_dump($indexInfo);
}
```
The above example would output something similar to:
```
object(MongoDB\Model\IndexInfo)#10 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["_id"]=>
int(1)
}
["name"]=>
string(4) "_id_"
["ns"]=>
string(9) "demo.zips"
}
object(MongoDB\Model\IndexInfo)#13 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["state"]=>
int(1)
}
["name"]=>
string(7) "state_1"
["ns"]=>
string(9) "demo.zips"
}
```
### Dropping Indexes
Indexes may be dropped via the [dropIndex()][dropindex] and
[dropIndexes()][dropindexes] methods. The following example drops a single index
by its name:
[dropindex]: ../classes/collection.md#dropindex
[dropindexes]: ../classes/collection.md#dropindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->dropIndex('state_1');
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
```
# Upgrade Guide
The MongoDB PHP Library and underlying [mongodb extension][ext-mongodb] have
notable API differences from the legacy [mongo extension][ext-mongo]. This page
will attempt to summarize those differences for the benefit of those upgrading
rom the legacy driver.
Additionally, a community-developed [mongo-php-adapter][adapter] library exists,
which implements the [mongo extension][ext-mongo] API using this library and the
new driver. While this adapter library is not officially supported by MongoDB,
it does bear mentioning.
[ext-mongo]: http://php.net/mongo
[ext-mongodb]: http://php.net/mongodb
[adapter]: https://github.com/alcaeus/mongo-php-adapter
## Collection API
This library's [MongoDB\Collection][collection] class implements MongoDB's
cross-driver [CRUD][crud-spec] and [Index Management][index-spec]
specifications. Although some method names have changed in accordance with the
new specifications, the new class provides the same functionality as the legacy
driver's [MongoCollection][mongocollection] class with some notable exceptions.
[collection]: classes/collection.md
[crud-spec]: https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst
[index-spec]: https://github.com/mongodb/specifications/blob/master/source/index-management.rst
[mongocollection]: http://php.net/mongocollection
### Old and New Methods
| [MongoCollection][mongocollection] | [MongoDB\Collection][collection] |
| --- | --- |
| [aggregate()](http://php.net/manual/en/mongocollection.aggregate.php) | [aggregate()](classes/collection.md#aggregate) |
| [aggregateCursor()](http://php.net/manual/en/mongocollection.aggregatecursor.php) | [aggregate()](classes/collection.md#aggregate) |
| [batchInsert()](http://php.net/manual/en/mongocollection.batchinsert.php) | [insertMany()](classes/collection.md#insertmany) |
| [count()](http://php.net/manual/en/mongocollection.count.php) | [count()](classes/collection.md#count) |
| [createDBRef()](http://php.net/manual/en/mongocollection.createdbref.php) | Not yet implemented ([PHPLIB-24][jira-dbref]) |
| [createIndex()](http://php.net/manual/en/mongocollection.createindex.php) | [createIndex()](classes/collection.md#createindex) |
| [deleteIndex()](http://php.net/manual/en/mongocollection.deleteindex.php) | [dropIndex()](classes/collection.md#dropindex) |
| [deleteIndexes()](http://php.net/manual/en/mongocollection.deleteindexes.php) | [dropIndexes()](classes/collection.md#dropindexes) |
| [drop()](http://php.net/manual/en/mongocollection.drop.php) | [drop()](classes/collection.md#drop) |
| [distinct()](http://php.net/manual/en/mongocollection.distinct.php) | [distinct()](classes/collection.md#distinct) |
| [ensureIndex()](http://php.net/manual/en/mongocollection.ensureindex.php) | [createIndex()](classes/collection.md#createindex) |
| [find()](http://php.net/manual/en/mongocollection.find.php) | [find()](classes/collection.md#find) |
| [findAndModify()](http://php.net/manual/en/mongocollection.findandmodify.php) | [findOneAndDelete()](classes/collection.md#findoneanddelete), [findOneAndReplace()](classes/collection.md#findoneandreplace), and [findOneAndUpdate()](classes/collection.md#findoneandupdate) |
| [findOne()](http://php.net/manual/en/mongocollection.findone.php) | [findOne()](classes/collection.md#findone) |
| [getDBRef()](http://php.net/manual/en/mongocollection.getdbref.php) | Not yet implemented ([PHPLIB-24][jira-dbref]) |
| [getIndexInfo()](http://php.net/manual/en/mongocollection.getindexinfo.php) | [listIndexes()](classes/collection.md#listindexes) |
| [getName()](http://php.net/manual/en/mongocollection.getname.php) | [getCollectionName()](classes/collection.md#getcollectionname) |
| [getReadPreference()](http://php.net/manual/en/mongocollection.getreadpreference.php) | Not implemented |
| [getSlaveOkay()](http://php.net/manual/en/mongocollection.getslaveokay.php) | Not implemented |
| [getWriteConcern()](http://php.net/manual/en/mongocollection.getwriteconcern.php) | Not implemented |
| [group()](http://php.net/manual/en/mongocollection.group.php) | Not yet implemented ([PHPLIB-177][jira-group]). Use [Database::command()](classes/database.md#command) for now. |
| [insert()](http://php.net/manual/en/mongocollection.insert.php) | [insertOne()](classes/collection.md#insertone) |
| [parallelCollectionScan()](http://php.net/manual/en/mongocollection.parallelcollectionscan.php) | Not implemented |
| [remove()](http://php.net/manual/en/mongocollection.remove.php) | [deleteMany()](classes/collection.md#deleteMany) and [deleteOne()](classes/collection.md#deleteone) |
| [save()](http://php.net/manual/en/mongocollection.save.php) | [insertOne()](classes/collection.md#insertone) or [replaceOne()](classes/collection.md#replaceone) with "upsert" option |
| [setReadPreference()](http://php.net/manual/en/mongocollection.setreadpreference.php) | Not implemented. Use [withOptions()](classes/collection.md#withoptions). |
| [setSlaveOkay()](http://php.net/manual/en/mongocollection.getslaveokay.php) | Not implemented |
| [setWriteConcern()](http://php.net/manual/en/mongocollection.setwriteconcern.php) | Not implemented. Use [withOptions()](classes/collection.md#withoptions). |
| [update()](http://php.net/manual/en/mongocollection.update.php) | [replaceOne()](classes/collection.md#replaceone), [updateMany()](classes/collection.md#updatemany), and [updateOne()](classes/collection.md#updateone) |
| [validate()](http://php.net/manual/en/mongocollection.validate.php) | Not implemented |
[jira-group]: https://jira.mongodb.org/browse/PHPLIB-177
[jira-dbref]: https://jira.mongodb.org/browse/PHPLIB-24
A guiding principle in designing the new APIs was that explicit method names
are preferable to overloaded terms found in the old API. For instance,
[MongoCollection::save()][save] and
[MongoCollection::findAndModify()][findandmodify] have very different modes of
operation, depending on their arguments. Methods were also split to distinguish
between [updating specific fields][update] and
[full-document replacement][replace].
[save]: http://php.net/manual/en/mongocollection.save.php
[findandmodify]: http://php.net/manual/en/mongocollection.findandmodify.php
[update]: https://docs.mongodb.org/manual/tutorial/modify-documents/#update-specific-fields-in-a-document
[replace]: https://docs.mongodb.org/manual/tutorial/modify-documents/#replace-the-document
### Group Command Helper
[MongoDB\Collection][collection] does not yet have a helper method for the
[group][group] command; however, that is planned in [PHPLIB-177][jira-group].
The following example demonstrates how to execute a group command using
[Database::command()](classes/database.md#command):
```php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'group' => [
'ns' => 'collection_name',
'key' => ['field_name' => 1],
'initial' => ['total' => 0],
'$reduce' => new MongoDB\BSON\Javascript('...'),
],
]);
$resultDocument = $cursor->toArray()[0];
```
[group]: https://docs.mongodb.org/manual/reference/command/group/
### MapReduce Command Helper
[MongoDB\Collection][collection] does not yet have a helper method for the
[mapReduce][mapReduce] command; however, that is planned in
[PHPLIB-53][jira-mapreduce]. The following example demonstrates how to execute a
mapReduce command using [Database::command()](classes/database.md#command):
```php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'mapReduce' => 'collection_name',
'map' => new MongoDB\BSON\Javascript('...'),
'reduce' => new MongoDB\BSON\Javascript('...'),
'out' => 'output_collection_name',
]);
$resultDocument = $cursor->toArray()[0];
```
[mapReduce]: https://docs.mongodb.org/manual/reference/command/mapReduce/
[jira-mapreduce]: https://jira.mongodb.org/browse/PHPLIB-53
### DBRef Helpers
[MongoDB\Collection][collection] does not yet have helper methods for working
with [DBRef][dbref] objects; however, that is planned in
[PHPLIB-24][jira-dbref].
[dbref]: https://docs.mongodb.org/manual/reference/database-references/#dbrefs
### MongoCollection::save() Removed
[MongoCollection::save()][save], which was syntactic sugar for an insert or
upsert operation, has been removed in favor of explicitly using
[insertOne()](classes/collection.md#insertone) or
[replaceOne()](classes/collection.md#replaceone) (with the "upsert" option).
![save() flowchart](img/save-flowchart.png)
While the [save()][save] method does have its uses for interactive environments,
such as the mongo shell, it was intentionally excluded from the
[CRUD][crud-spec] specification for language drivers. Generally, application
code should know if the document has an identifier and be able to explicitly
insert or replace the document and handle the returned InsertResult or
UpdateResult, respectively. This also helps avoid inadvertent and potentially
dangerous [full-document replacements][replace].
### MongoWriteBatch
The legacy driver's [MongoWriteBatch][batch] classes have been replaced with a
general-purpose [bulkWrite()](classes/collection.md#bulkwrite) method. Whereas
the legacy driver only allowed bulk operations of the same time, the new method
allows operations to be mixed (e.g. inserts, updates, and deletes).
[batch]: http://php.net/manual/en/class.mongowritebatch.php
......@@ -7,13 +7,19 @@ theme: readthedocs
pages:
- 'Home': 'index.md'
- 'Getting Started': 'getting-started.md'
- 'Example Data': 'example-data.md'
- 'Upgrade Guide': 'upgrade-guide.md'
- Tutorial:
- 'CRUD Operations': 'tutorial/crud.md'
- 'Indexes': 'tutorial/indexes.md'
- 'Example Data': 'tutorial/example-data.md'
- Classes:
- 'Client': 'classes/client.md'
- 'Database': 'classes/database.md'
- 'Collection': 'classes/collection.md'
markdown_extensions:
- def_list
- fenced_code
- smarty
- toc:
permalink: true
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