Commit e2c4a0c5 authored by Jeremy Mikola's avatar Jeremy Mikola

Split Collection docs into API, tutorial, and upgrade guide

parent 84510286
This diff is collapsed.
# 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 # Example Data
Some examples in this documentation use example data fixtures from Some examples in this documentation use example data fixtures from
[zips.json](http://media.mongodb.org/zips.json). This is a dataset comprised of [zips.json][zips]. This is a dataset comprised of United States postal codes,
United States postal codes, populations, and geographic locations. populations, and geographic locations.
Importing the dataset into MongoDB can be done in several ways. The following Importing the dataset into MongoDB can be done in several ways. The following
example uses [PHP driver](http://php.net/mongodb) (i.e. `mongodb` extension). example uses [mongodb extension][ext-mongodb]:
[zips]: http://media.mongodb.org/zips.json
[ext-mongodb]: http://php.net/mongodb
``` ```
<?php
$file = 'http://media.mongodb.org/zips.json'; $file = 'http://media.mongodb.org/zips.json';
$zips = file($file, FILE_IGNORE_NEW_LINES); $zips = file($file, FILE_IGNORE_NEW_LINES);
...@@ -30,10 +35,11 @@ Executing this script should yield the following output: ...@@ -30,10 +35,11 @@ Executing this script should yield the following output:
Inserted 29353 documents Inserted 29353 documents
``` ```
You may also import the dataset using the You may also import the dataset using the [mongoimport][mongoimport] command,
[`mongoimport`](http://docs.mongodb.org/manual/reference/program/mongoimport/) which is included with MongoDB:
command, which is included with MongoDB:
``` [mongoimport]: http://docs.mongodb.org/manual/reference/program/mongoimport/
```bash
$ mongoimport --db demo --collection zips --file zips.json --drop $ mongoimport --db demo --collection zips --file zips.json --drop
``` ```
# Indexes
Indexes may be managed via the [MongoDB\Collection][collection] class, which
implements MongoDB's cross-driver [Index Management][index-spec] and
[Enumerating Indexes][enum-spec] specifications. This page will demonstrate how
to create, list, and drop indexes using the library. General information on how
indexes work in MongoDB may be found in the [MongoDB manual][indexes].
[collection]: ../classes/collection.md
[index-spec]: https://github.com/mongodb/specifications/blob/master/source/index-management.rst
[enum-spec]: https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst
[indexes]: https://docs.mongodb.org/manual/indexes/
## Creating Indexes
Indexes may be created via the [createIndex()][createindex] and
[createIndexes()][createindexes] methods. The following example creates an
ascending index on the "state" field:
[createindex]: ../classes/collection.md#createindex
[createindexes]: ../classes/collection.md#createindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->createIndex(['state' => 1]);
var_dump($result);
```
Creating an index will return its name, which is automatically generated from
its specification (i.e. fields and orderings). The above example would output
something similar to:
```
string(7) "state_1"
```
### Enumerating Indexes
Information about indexes in a collection may be obtained via the
[listIndexes()][listindexes] method, which returns an iterator of
MongoDB\Model\IndexInfo objects. The following example lists all indexes in the
"demo.zips" collection:
[listindexes]: ../classes/collection.md#listindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
foreach ($collection->listIndexes() as $indexInfo) {
var_dump($indexInfo);
}
```
The above example would output something similar to:
```
object(MongoDB\Model\IndexInfo)#10 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["_id"]=>
int(1)
}
["name"]=>
string(4) "_id_"
["ns"]=>
string(9) "demo.zips"
}
object(MongoDB\Model\IndexInfo)#13 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["state"]=>
int(1)
}
["name"]=>
string(7) "state_1"
["ns"]=>
string(9) "demo.zips"
}
```
### Dropping Indexes
Indexes may be dropped via the [dropIndex()][dropindex] and
[dropIndexes()][dropindexes] methods. The following example drops a single index
by its name:
[dropindex]: ../classes/collection.md#dropindex
[dropindexes]: ../classes/collection.md#dropindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->dropIndex('state_1');
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
```
# Upgrade Guide
The MongoDB PHP Library and underlying [mongodb extension][ext-mongodb] have
notable API differences from the legacy [mongo extension][ext-mongo]. This page
will attempt to summarize those differences for the benefit of those upgrading
rom the legacy driver.
Additionally, a community-developed [mongo-php-adapter][adapter] library exists,
which implements the [mongo extension][ext-mongo] API using this library and the
new driver. While this adapter library is not officially supported by MongoDB,
it does bear mentioning.
[ext-mongo]: http://php.net/mongo
[ext-mongodb]: http://php.net/mongodb
[adapter]: https://github.com/alcaeus/mongo-php-adapter
## Collection API
This library's [MongoDB\Collection][collection] class implements MongoDB's
cross-driver [CRUD][crud-spec] and [Index Management][index-spec]
specifications. Although some method names have changed in accordance with the
new specifications, the new class provides the same functionality as the legacy
driver's [MongoCollection][mongocollection] class with some notable exceptions.
[collection]: classes/collection.md
[crud-spec]: https://github.com/mongodb/specifications/blob/master/source/crud/crud.rst
[index-spec]: https://github.com/mongodb/specifications/blob/master/source/index-management.rst
[mongocollection]: http://php.net/mongocollection
### Old and New Methods
| [MongoCollection][mongocollection] | [MongoDB\Collection][collection] |
| --- | --- |
| [aggregate()](http://php.net/manual/en/mongocollection.aggregate.php) | [aggregate()](classes/collection.md#aggregate) |
| [aggregateCursor()](http://php.net/manual/en/mongocollection.aggregatecursor.php) | [aggregate()](classes/collection.md#aggregate) |
| [batchInsert()](http://php.net/manual/en/mongocollection.batchinsert.php) | [insertMany()](classes/collection.md#insertmany) |
| [count()](http://php.net/manual/en/mongocollection.count.php) | [count()](classes/collection.md#count) |
| [createDBRef()](http://php.net/manual/en/mongocollection.createdbref.php) | Not yet implemented ([PHPLIB-24][jira-dbref]) |
| [createIndex()](http://php.net/manual/en/mongocollection.createindex.php) | [createIndex()](classes/collection.md#createindex) |
| [deleteIndex()](http://php.net/manual/en/mongocollection.deleteindex.php) | [dropIndex()](classes/collection.md#dropindex) |
| [deleteIndexes()](http://php.net/manual/en/mongocollection.deleteindexes.php) | [dropIndexes()](classes/collection.md#dropindexes) |
| [drop()](http://php.net/manual/en/mongocollection.drop.php) | [drop()](classes/collection.md#drop) |
| [distinct()](http://php.net/manual/en/mongocollection.distinct.php) | [distinct()](classes/collection.md#distinct) |
| [ensureIndex()](http://php.net/manual/en/mongocollection.ensureindex.php) | [createIndex()](classes/collection.md#createindex) |
| [find()](http://php.net/manual/en/mongocollection.find.php) | [find()](classes/collection.md#find) |
| [findAndModify()](http://php.net/manual/en/mongocollection.findandmodify.php) | [findOneAndDelete()](classes/collection.md#findoneanddelete), [findOneAndReplace()](classes/collection.md#findoneandreplace), and [findOneAndUpdate()](classes/collection.md#findoneandupdate) |
| [findOne()](http://php.net/manual/en/mongocollection.findone.php) | [findOne()](classes/collection.md#findone) |
| [getDBRef()](http://php.net/manual/en/mongocollection.getdbref.php) | Not yet implemented ([PHPLIB-24][jira-dbref]) |
| [getIndexInfo()](http://php.net/manual/en/mongocollection.getindexinfo.php) | [listIndexes()](classes/collection.md#listindexes) |
| [getName()](http://php.net/manual/en/mongocollection.getname.php) | [getCollectionName()](classes/collection.md#getcollectionname) |
| [getReadPreference()](http://php.net/manual/en/mongocollection.getreadpreference.php) | Not implemented |
| [getSlaveOkay()](http://php.net/manual/en/mongocollection.getslaveokay.php) | Not implemented |
| [getWriteConcern()](http://php.net/manual/en/mongocollection.getwriteconcern.php) | Not implemented |
| [group()](http://php.net/manual/en/mongocollection.group.php) | Not yet implemented ([PHPLIB-177][jira-group]). Use [Database::command()](classes/database.md#command) for now. |
| [insert()](http://php.net/manual/en/mongocollection.insert.php) | [insertOne()](classes/collection.md#insertone) |
| [parallelCollectionScan()](http://php.net/manual/en/mongocollection.parallelcollectionscan.php) | Not implemented |
| [remove()](http://php.net/manual/en/mongocollection.remove.php) | [deleteMany()](classes/collection.md#deleteMany) and [deleteOne()](classes/collection.md#deleteone) |
| [save()](http://php.net/manual/en/mongocollection.save.php) | [insertOne()](classes/collection.md#insertone) or [replaceOne()](classes/collection.md#replaceone) with "upsert" option |
| [setReadPreference()](http://php.net/manual/en/mongocollection.setreadpreference.php) | Not implemented. Use [withOptions()](classes/collection.md#withoptions). |
| [setSlaveOkay()](http://php.net/manual/en/mongocollection.getslaveokay.php) | Not implemented |
| [setWriteConcern()](http://php.net/manual/en/mongocollection.setwriteconcern.php) | Not implemented. Use [withOptions()](classes/collection.md#withoptions). |
| [update()](http://php.net/manual/en/mongocollection.update.php) | [replaceOne()](classes/collection.md#replaceone), [updateMany()](classes/collection.md#updatemany), and [updateOne()](classes/collection.md#updateone) |
| [validate()](http://php.net/manual/en/mongocollection.validate.php) | Not implemented |
[jira-group]: https://jira.mongodb.org/browse/PHPLIB-177
[jira-dbref]: https://jira.mongodb.org/browse/PHPLIB-24
A guiding principle in designing the new APIs was that explicit method names
are preferable to overloaded terms found in the old API. For instance,
[MongoCollection::save()][save] and
[MongoCollection::findAndModify()][findandmodify] have very different modes of
operation, depending on their arguments. Methods were also split to distinguish
between [updating specific fields][update] and
[full-document replacement][replace].
[save]: http://php.net/manual/en/mongocollection.save.php
[findandmodify]: http://php.net/manual/en/mongocollection.findandmodify.php
[update]: https://docs.mongodb.org/manual/tutorial/modify-documents/#update-specific-fields-in-a-document
[replace]: https://docs.mongodb.org/manual/tutorial/modify-documents/#replace-the-document
### Group Command Helper
[MongoDB\Collection][collection] does not yet have a helper method for the
[group][group] command; however, that is planned in [PHPLIB-177][jira-group].
The following example demonstrates how to execute a group command using
[Database::command()](classes/database.md#command):
```php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'group' => [
'ns' => 'collection_name',
'key' => ['field_name' => 1],
'initial' => ['total' => 0],
'$reduce' => new MongoDB\BSON\Javascript('...'),
],
]);
$resultDocument = $cursor->toArray()[0];
```
[group]: https://docs.mongodb.org/manual/reference/command/group/
### MapReduce Command Helper
[MongoDB\Collection][collection] does not yet have a helper method for the
[mapReduce][mapReduce] command; however, that is planned in
[PHPLIB-53][jira-mapreduce]. The following example demonstrates how to execute a
mapReduce command using [Database::command()](classes/database.md#command):
```php
<?php
$database = (new MongoDB\Client)->selectDatabase('db_name');
$cursor = $database->command([
'mapReduce' => 'collection_name',
'map' => new MongoDB\BSON\Javascript('...'),
'reduce' => new MongoDB\BSON\Javascript('...'),
'out' => 'output_collection_name',
]);
$resultDocument = $cursor->toArray()[0];
```
[mapReduce]: https://docs.mongodb.org/manual/reference/command/mapReduce/
[jira-mapreduce]: https://jira.mongodb.org/browse/PHPLIB-53
### DBRef Helpers
[MongoDB\Collection][collection] does not yet have helper methods for working
with [DBRef][dbref] objects; however, that is planned in
[PHPLIB-24][jira-dbref].
[dbref]: https://docs.mongodb.org/manual/reference/database-references/#dbrefs
### MongoCollection::save() Removed
[MongoCollection::save()][save], which was syntactic sugar for an insert or
upsert operation, has been removed in favor of explicitly using
[insertOne()](classes/collection.md#insertone) or
[replaceOne()](classes/collection.md#replaceone) (with the "upsert" option).
![save() flowchart](img/save-flowchart.png)
While the [save()][save] method does have its uses for interactive environments,
such as the mongo shell, it was intentionally excluded from the
[CRUD][crud-spec] specification for language drivers. Generally, application
code should know if the document has an identifier and be able to explicitly
insert or replace the document and handle the returned InsertResult or
UpdateResult, respectively. This also helps avoid inadvertent and potentially
dangerous [full-document replacements][replace].
### MongoWriteBatch
The legacy driver's [MongoWriteBatch][batch] classes have been replaced with a
general-purpose [bulkWrite()](classes/collection.md#bulkwrite) method. Whereas
the legacy driver only allowed bulk operations of the same time, the new method
allows operations to be mixed (e.g. inserts, updates, and deletes).
[batch]: http://php.net/manual/en/class.mongowritebatch.php
...@@ -7,13 +7,19 @@ theme: readthedocs ...@@ -7,13 +7,19 @@ theme: readthedocs
pages: pages:
- 'Home': 'index.md' - 'Home': 'index.md'
- 'Getting Started': 'getting-started.md' - 'Getting Started': 'getting-started.md'
- 'Example Data': 'example-data.md' - 'Upgrade Guide': 'upgrade-guide.md'
- Tutorial:
- 'CRUD Operations': 'tutorial/crud.md'
- 'Indexes': 'tutorial/indexes.md'
- 'Example Data': 'tutorial/example-data.md'
- Classes: - Classes:
- 'Client': 'classes/client.md' - 'Client': 'classes/client.md'
- 'Database': 'classes/database.md' - 'Database': 'classes/database.md'
- 'Collection': 'classes/collection.md' - 'Collection': 'classes/collection.md'
markdown_extensions: markdown_extensions:
- def_list
- fenced_code
- smarty - smarty
- toc: - toc:
permalink: true permalink: true
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