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

Remove Markdown documentation (i.e gh-pages)

parent 0b68ed61
# MongoDB\Client
The MongoDB\Client class serves as an entry point for the library. It is the
preferred class for connecting to a MongoDB server or cluster of servers and
serves as a gateway for accessing individual databases and collections. It is
analogous to the driver's [MongoDB\Driver\Manager][manager] class, which it
composes.
[manager]: http://php.net/mongodb-driver-manager
---
## __construct()
```php
function __construct($uri = 'mongodb://localhost:27017', array $uriOptions = [], array $driverOptions = [])
```
Constructs a new Client instance.
Additional URI options may be provided as the second argument and will take
precedence over any like options present in the URI string (e.g. authentication
credentials, query string parameters).
Driver options may be provided as the third argument. In addition to any options
supported by the extension, this library allows you to specify a default
type map to apply to the cursors it creates. A more thorough description of type
maps may be found in the driver's [Persistence documentation][typemap].
[typemap]: http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps
### Supported URI Options
See [MongoDB\Driver\Manager::__construct()][manager-construct] and the
[MongoDB manual][connection-string].
[manager-construct]: http://php.net/manual/en/mongodb-driver-manager.construct.php
[connection-string]: https://docs.mongodb.org/manual/reference/connection-string/
### Supported Driver Options
typeMap (array)
: Default type map for cursors and BSON documents.
### Example
By default, the driver connects to a standalone server on localhost via port
27017. The following example demonstrates how to connect to a replica set.
Additionally, it demonstrates a replica set with a custom read preference:
```
<?php
$client = new MongoDB\Client(
'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet',
[
'readPreference' => 'secondaryPreferred'
]
);
```
By default, the library will unserialize BSON documents and arrays as
MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray objects, respectively.
The following example demonstrates how to have the library unserialize
everything as a PHP array, as was done in the legacy
[mongo extension][ext-mongo]:
[ext-mongo]: http://php.net/mongo
```
<?php
$client = new MongoDB\Client(
null,
[],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
);
```
### See Also
* [MongoDB\Driver\Manager::__construct()][manager-construct]
* [MongoDB Manual: Connection String][connection-string]
---
## __get()
```php
function __get($databaseName): MongoDB\Database
```
Select a database.
The Database will inherit options (e.g. read preference, type map) from the
Client object. Use [selectDatabase()](#selectdatabase) to override any options.
**Note:** databases whose names contain special characters (e.g. "-") may be
selected with complex syntax (e.g. `$client->{"that-database"}`) or
[selectDatabase()](#selectdatabase).
### Example
The following example selects the "demo" and "another-app" databases:
```
<?php
$client = new MongoDB\Client;
$demo = $client->demo;
$anotherApp = $client->{'another-app'};
```
### See Also
* [MongoDB\Client::selectDatabase()](#selectdatabase)
* [PHP Manual: Property Overloading](http://php.net/oop5.overloading#object.get)
---
## dropDatabase
```php
function dropDatabase($databaseName, array $options = []): array|object
```
Drop a database. Returns the command result document.
### Supported Options
typeMap (array)
: Type map for BSON deserialization. This will only be used for the returned
command result document.
### Example
The following example drops the "demo" database:
```
<?php
$client = new MongoDB\Client;
$result = $client->dropDatabase('demo');
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["dropped"]=>
string(4) "demo"
["ok"]=>
float(1)
}
}
```
### See Also
* [MongoDB\Database::drop()](database.md#drop)
* [MongoDB Manual: dropDatabase command](http://docs.mongodb.org/manual/reference/command/dropDatabase/)
---
## listDatabases()
```php
function listDatabases(array $options = []): MongoDB\Model\DatabaseInfoIterator
```
Returns information for all database on the server. Elements in the returned
iterator will be MongoDB\Model\DatabaseInfo objects.
### Supported Options
maxTimeMS (integer)
: The maximum amount of time to allow the query to run.
### Example
The following example lists all databases on the server:
```
<?php
$client = new MongoDB\Client;
foreach ($client->listDatabases() as $databaseInfo) {
var_dump($databaseInfo);
}
```
The above example would output something similar to:
```
object(MongoDB\Model\DatabaseInfo)#4 (3) {
["name"]=>
string(5) "local"
["sizeOnDisk"]=>
float(65536)
["empty"]=>
bool(false)
}
object(MongoDB\Model\DatabaseInfo)#7 (3) {
["name"]=>
string(4) "test"
["sizeOnDisk"]=>
float(32768)
["empty"]=>
bool(false)
}
```
### See Also
* [MongoDB Manual: listDatabases command](http://docs.mongodb.org/manual/reference/command/listDatabases/)
---
## selectCollection()
```php
function selectCollection($databaseName, $collectionName, array $options = []): MongoDB\Collection
```
Select a collection on the server.
The Collection will inherit options (e.g. read preference, type map) from the
Client object unless otherwise specified.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for collection operations. Defaults to the
Client's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for collection operations. Defaults to
the Client's read preference.
typeMap (array)
: Default type map for cursors and BSON documents. Defaults to the Client's
type map.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for collection operations. Defaults to the
Client's write concern.
### Example
The following example selects the "demo.users" collection:
```
<?php
$client = new MongoDB\Client;
$collection = $client->selectCollection('demo', 'users');
```
The following examples selects the "demo.users" collection with a custom read
preference:
```
<?php
$client = new MongoDB\Client;
$collection = $client->selectCollection(
'demo',
'users',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
```
### See Also
* [MongoDB\Collection::__construct()](collection.md#__construct)
* [MongoDB\Client::__get()](#__get)
---
## selectDatabase()
```php
function selectDatabase($databaseName array $options = []): MongoDB\Collection
```
Select a database on the server.
The Database will inherit options (e.g. read preference, type map) from the
Client object unless otherwise specified.
### Supported Options
readConcern (MongoDB\Driver\ReadConcern)
: The default read concern to use for database operations. Defaults to the
Client's read concern.
readPreference (MongoDB\Driver\ReadPreference)
: The default read preference to use for database operations. Defaults to the
Client's read preference.
typeMap (array)
: Default type map for cursors and BSON documents. Defaults to the Client's
type map.
writeConcern (MongoDB\Driver\WriteConcern)
: The default write concern to use for database operations. Defaults to the
Client's write concern.
### Example
The following example selects the "demo" database:
```
<?php
$client = new MongoDB\Client;
$db = $client->selectDatabase('demo');
```
The following examples selects the "demo" database with a custom read
preference:
```
<?php
$client = new MongoDB\Client;
$db = $client->selectDatabase(
'demo',
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
]
);
```
### See Also
* [MongoDB\Database::__construct()](database.md#__construct)
* [MongoDB\Client::__get()](#__get)
---
This diff is collapsed.
This diff is collapsed.
# Getting Started
### Requirements
Since this library is only a high-level abstraction for the driver, it requires
that the `mongodb` extension be installed:
```
$ pecl install mongodb
$ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
```
Instructions for installing the `mongodb` extension on HHVM may be found in the
[Installation with HHVM](http://php.net/manual/en/mongodb.tutorial.install.hhvm.php)
article in the driver documentation.
### Installation
The preferred method of installing this library is with
[Composer](https://getcomposer.org/) by running the following from your project
root:
```
$ composer require "mongodb/mongodb=^1.0.0"
```
While not recommended, the package may also be installed manually via source
tarballs attached to
[GitHub releases](https://github.com/mongodb/mongo-php-library/releases).
### Configure Autoloading
Once the library is installed, ensure that your application includes Composer's
autoloader.
```
// This path should point to Composer's autoloader
require_once __DIR__ . "/vendor/autoload.php";
```
More information on this setup may be found in Composer's
[autoloading documentation](https://getcomposer.org/doc/01-basic-usage.md#autoloading).
If you have installed the package manually (e.g. from a source tarball), you
will likely need configure autoloading manually:
* Map the top-level `MongoDB\` namespace to the `src/` directory using your
preferred autoloader implementation
* Manually require the `src/functions.php` file, since PHP does not yet support
function autoloading
# MongoDB PHP Library
This library provides a high-level abstraction around the lower-level
[PHP driver](https://php.net/mongodb) (i.e. the `mongodb` extension).
While the extension provides a limited API for executing commands, queries, and
write operations, this library implements an API similar to that of the
[legacy PHP driver](http://php.net/manual/en/book.mongo.php). It contains
abstractions for client, database, and collection objects, and provides methods
for CRUD operations and common commands (e.g. index and collection management).
Support for GridFS is forthcoming.
If you are developing an application with MongoDB, you should consider using
this library, or another high-level abstraction, instead of the extension alone.
For additional information about this library and the ``mongodb`` extension,
see the [Architecture Overview](http://php.net/manual/en/mongodb.overview.php)
article in the driver documentation. [Derick Rethans](http://derickrethans.nl/)
has also written a series of blog posts entitled *New MongoDB Drivers for PHP
and HHVM*:
* [Part One: History](http://derickrethans.nl/new-drivers.html)
* [Part Two: Architecture](http://derickrethans.nl/new-drivers-part2.html)
* [Part Three: Cursor Behaviour](https://derickrethans.nl/new-drivers-part3-cursor.html)
## API Documentation
Generated API documentation for the library is available at:
* [http://mongodb.github.io/mongo-php-library/api](http://mongodb.github.io/mongo-php-library/api)
## MongoDB Tutorial
If you are a new MongoDB user, these links should help you become more familiar
with MongoDB and introduce some of the concepts and terms you will encounter in
this documentation:
* [Introduction to CRUD operations in MongoDB](http://docs.mongodb.org/manual/core/crud-introduction/)
* [What is a MongoDB document?](http://docs.mongodb.org/manual/core/document/)
* [MongoDB's *dot notation* for accessing document properties](http://docs.mongodb.org/manual/core/document/#dot-notation)
* [ObjectId: MongoDB's document identifier](http://docs.mongodb.org/manual/reference/object-id/)
# BSON Conversion
## Deserialization
By default, the library returns BSON documents and arrays as
MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray objects, respectively.
Both of those classes extend PHP's [ArrayObject][arrayobject] class and
implement the driver's [MongoDB\BSON\Serializable][serializable] and
[MongoDB\BSON\Unserializable][unserializable] interfaces.
[arrayobject]: http://php.net/arrayobject
[serializable]: http://php.net/mongodb-bson-serializable
[unserializable]: http://php.net/mongodb-bson-unserializable
## Type Maps
Most methods that read data from MongoDB support a "typeMap" option, which
allows control over how BSON is converted to PHP. Additionally, the
[MongoDB\Client][client], [MongoDB\Database][database], and
[MongoDB\Collection][collection] classes accept a "typeMap" option, which will
apply to any supporting methods and selected classes by default.
[client]: ../classes/client.md
[database]: ../classes/database.md
[collection]: ../classes/collection.md
The [MongoDB\Client][client], [MongoDB\Database][database], and
[MongoDB\Collection][collection] classes use the following type map by default:
```php
[
'array' => 'MongoDB\Model\BSONArray',
'document' => 'MongoDB\Model\BSONDocument',
'root' => 'MongoDB\Model\BSONDocument',
]
```
## Persistable Classes
Classes implementing [MongoDB\BSON\Persistable][persistable] will be serialized
and deserialized according to the [Persistence][persistence] specification. This
behavior occurs by default in the [driver][ext-mongodb] and does not require use
of the "typeMap" option.
[persistable]: http://php.net/mongodb-bson-persistable
[persistence]: http://php.net/manual/en/mongodb.persistence.php
[ext-mongodb]: https://php.net/mongodb
Given the following class definition:
```
<?php
class Person implements MongoDB\BSON\Persistable
{
private $id;
private $name;
private $createdAt;
public function __construct($name)
{
$this->id = new MongoDB\BSON\ObjectID;
$this->name = (string) $name;
// Get current time in milliseconds since the epoch
$msec = floor(microtime(true) * 1000);
$this->createdAt = new MongoDB\BSON\UTCDateTime($msec);
}
function bsonSerialize()
{
return [
'_id' => $this->id,
'name' => $this->name,
'createdAt' => $this->createdAt,
];
}
function bsonUnserialize(array $data)
{
$this->id = $data['_id'];
$this->name = $data['name'];
$this->createdAt = $data['createdAt'];
}
}
```
The following example constructs a Person object, inserts it into the database,
and reads it back as an object of the same type (without the use of the
"typeMap" option):
```
<?php
$collection = (new MongoDB\Client)->demo->persons;
$result = $collection->insertOne(new Person('Bob'));
$person = $collection->findOne(['_id' => $result->getInsertedId()]);
var_dump($person);
```
The above example would output something similar to:
```
object(Person)#18 (3) {
["id":"Person":private]=>
object(MongoDB\BSON\ObjectID)#15 (1) {
["oid"]=>
string(24) "56fad2c36118fd2e9820cfc1"
}
["name":"Person":private]=>
string(3) "Bob"
["createdAt":"Person":private]=>
object(MongoDB\BSON\UTCDateTime)#17 (1) {
["milliseconds"]=>
int(1459278531218)
}
}
```
The same document in the MongoDB shell might display as:
```
> db.persons.findOne()
{
"_id" : ObjectId("56fad2c36118fd2e9820cfc1"),
"__pclass" : BinData(128,"UGVyc29u"),
"name" : "Bob",
"createdAt" : ISODate("2016-03-29T19:08:51.218Z")
}
```
**Note:** [MongoDB\BSON\Persistable][persistable] may only be used for root and
embedded BSON documents; BSON arrays are not supported.
## Emulating the Legacy Driver
The legacy [mongo extension][ext-mongo] returned both BSON documents and
arrays as PHP arrays. While PHP arrays are convenient to work with, this
behavior was problematic for several reasons:
[ext-mongo]: http://php.net/mongo
* Different BSON types could deserialize to the same PHP value (e.g.
`{"0": "foo"}` and `["foo"]`), which made it impossible to infer the
original BSON type.
* Numerically indexed PHP arrays would be serialized as BSON documents if there
was a gap in their key sequence. Such gaps were easily (and inadvertently)
caused by unsetting a key to remove an element and forgetting to reindex the
array.
The libary's MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray classes
address these concerns by preserving the BSON type information during
serialization and deserialization; however, some users may still prefer the
legacy behavior. If desired, the following "typeMap" option can be used to have
the library return everything as a PHP array:
```
<?php
$client = new MongoDB\Client(
null,
[],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
);
$document = $client->demo->zips->findOne(
['_id' => '94301'],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
);
var_dump($document);
```
The above example would output something similar to:
```
array(5) {
["_id"]=>
string(5) "94301"
["city"]=>
string(9) "PALO ALTO"
["loc"]=>
array(2) {
[0]=>
float(-122.149685)
[1]=>
float(37.444324)
}
["pop"]=>
int(15965)
["state"]=>
string(2) "CA"
}
```
# Database Commands
While the library provides helpers for some common database commands, it is far
from an [exhaustive list][command-list]. This page will demonstrate how to
execute arbitrary commands on the MongoDB server via the
[Database::command()][command] method and access their results.
[command-list]: https://docs.mongodb.org/manual/reference/command/
[command]: ../classes/database.md#command
## Single Result Documents
The [command()][command] method always returns a
[MongoDB\Driver\Cursor][cursor]. Unless otherwise stated in the MongoDB
documentation, command responses are returned as a single document. Reading such
a result will require iterating on the cursor and accessing the first (and only)
document, like so:
[cursor]: http://php.net/mongodb-driver-cursor
```
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command(['ping' => 1]);
var_dump($cursor->toArray()[0]);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#2 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
```
## Iterable Results as a Command Cursor
Some commands, such as [listCollections][listcollections], return their results
via an iterable command cursor. In this case, the returned
[MongoDB\Driver\Cursor][cursor] may be iterated in the same manner as one might
do with a [Collection::find()][find] query, like so:
[listcollections]: http://docs.mongodb.org/manual/reference/command/listCollections/
[find]: ../classes/collection.md#find
```
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command(['listCollections' => 1]);
foreach ($cursor as $collection) {
echo $collection['name'], "\n";
}
```
The above example would output something similar to:
```
persons
posts
zips
```
**Note:** at the protocol level, commands that support a cursor actually return
a single result document with the essential ingredients for constructing the
command cursor (i.e. the cursor's ID, namespace, and first batch of results);
however, the driver's [executeCommand()][executecommand] method already detects
such a result and constructs the iterable command cursor for us.
[executecommand]: http://php.net/manual/en/mongodb-driver-manager.executecommand.php
## Specifying a Read Preference
Some commands, such as [createUser][createUser], can only be executed on a
primary server. Command helpers in the library, such as
[Database::drop()][drop], know to apply their own read preference if necessary;
however, [command()][command] is a generic method and has no special knowledge.
It defaults to the read preference of the Database object on which it is
invoked. In such cases, it can be helpful to explicitly specify the correct read
preference, like so:
[createUser]: https://docs.mongodb.org/manual/reference/command/createUser/
[drop]: ../classes/database.md#drop
```
<?php
$db = (new MongoDB\Client)->demo;
$cursor = $db->command(
[
'createUser' => 'username',
'pwd' => 'password',
'roles' => ['readWrite'],
],
[
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY),
]
);
var_dump($cursor->toArray()[0]);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#8 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["ok"]=>
float(1)
}
}
```
This diff is collapsed.
# Example Data
Some examples in this documentation use example data fixtures from
[zips.json][zips]. This is a dataset comprised of United States postal codes,
populations, and geographic locations.
Importing the dataset into MongoDB can be done in several ways. The following
example uses [mongodb extension][ext-mongodb]:
[zips]: http://media.mongodb.org/zips.json
[ext-mongodb]: http://php.net/mongodb
```
<?php
$file = 'http://media.mongodb.org/zips.json';
$zips = file($file, FILE_IGNORE_NEW_LINES);
$bulk = new MongoDB\Driver\BulkWrite;
foreach ($zips as $string) {
$document = json_decode($string);
$bulk->insert($document);
}
$manager = new MongoDB\Driver\Manager('mongodb://localhost');
$result = $manager->executeBulkWrite('demo.zips', $bulk);
printf("Inserted %d documents\n", $result->getInsertedCount());
```
Executing this script should yield the following output:
```
Inserted 29353 documents
```
You may also import the dataset using the [mongoimport][mongoimport] command,
which is included with MongoDB:
[mongoimport]: http://docs.mongodb.org/manual/reference/program/mongoimport/
```bash
$ mongoimport --db demo --collection zips --file zips.json --drop
```
# Indexes
Indexes may be managed via the [MongoDB\Collection][collection] class, which
implements MongoDB's cross-driver [Index Management][index-spec] and
[Enumerating Indexes][enum-spec] specifications. This page will demonstrate how
to create, list, and drop indexes using the library. General information on how
indexes work in MongoDB may be found in the [MongoDB manual][indexes].
[collection]: ../classes/collection.md
[index-spec]: https://github.com/mongodb/specifications/blob/master/source/index-management.rst
[enum-spec]: https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst
[indexes]: https://docs.mongodb.org/manual/indexes/
## Creating Indexes
Indexes may be created via the [createIndex()][createindex] and
[createIndexes()][createindexes] methods. The following example creates an
ascending index on the "state" field:
[createindex]: ../classes/collection.md#createindex
[createindexes]: ../classes/collection.md#createindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->createIndex(['state' => 1]);
var_dump($result);
```
Creating an index will return its name, which is automatically generated from
its specification (i.e. fields and orderings). The above example would output
something similar to:
```
string(7) "state_1"
```
### Enumerating Indexes
Information about indexes in a collection may be obtained via the
[listIndexes()][listindexes] method, which returns an iterator of
MongoDB\Model\IndexInfo objects. The following example lists all indexes in the
"demo.zips" collection:
[listindexes]: ../classes/collection.md#listindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
foreach ($collection->listIndexes() as $indexInfo) {
var_dump($indexInfo);
}
```
The above example would output something similar to:
```
object(MongoDB\Model\IndexInfo)#10 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["_id"]=>
int(1)
}
["name"]=>
string(4) "_id_"
["ns"]=>
string(9) "demo.zips"
}
object(MongoDB\Model\IndexInfo)#13 (4) {
["v"]=>
int(1)
["key"]=>
array(1) {
["state"]=>
int(1)
}
["name"]=>
string(7) "state_1"
["ns"]=>
string(9) "demo.zips"
}
```
### Dropping Indexes
Indexes may be dropped via the [dropIndex()][dropindex] and
[dropIndexes()][dropindexes] methods. The following example drops a single index
by its name:
[dropindex]: ../classes/collection.md#dropindex
[dropindexes]: ../classes/collection.md#dropindexes
```
<?php
$collection = (new MongoDB\Client)->demo->zips;
$result = $collection->dropIndex('state_1');
var_dump($result);
```
The above example would output something similar to:
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["nIndexesWas"]=>
int(2)
["ok"]=>
float(1)
}
}
```
This diff is collapsed.
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