Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Contribute to GitLab
Sign in
Toggle navigation
M
mongo-php-library
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
sinan
mongo-php-library
Commits
a2d91319
Commit
a2d91319
authored
Mar 24, 2016
by
Jeremy Mikola
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Split Database docs into API and tutorial
parent
f6d110f9
Hide whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
475 additions
and
84 deletions
+475
-84
collection.md
docs/classes/collection.md
+2
-0
database.md
docs/classes/database.md
+347
-84
commands.md
docs/tutorial/commands.md
+125
-0
mkdocs.yml
mkdocs.yml
+1
-0
No files found.
docs/classes/collection.md
View file @
a2d91319
...
@@ -57,6 +57,7 @@ writeConcern (MongoDB\Driver\WriteConcern)
...
@@ -57,6 +57,7 @@ writeConcern (MongoDB\Driver\WriteConcern)
### See Also
### See Also
*
[
MongoDB\Collection::withOptions()
](
#withoptions
)
*
[
MongoDB\Collection::withOptions()
](
#withoptions
)
*
[
MongoDB\Database::selectCollection()
](
database.md#selectcollection
)
---
---
...
@@ -411,6 +412,7 @@ object(MongoDB\Model\BSONDocument)#11 (1) {
...
@@ -411,6 +412,7 @@ object(MongoDB\Model\BSONDocument)#11 (1) {
### See Also
### See Also
*
[
MongoDB\Database::dropCollection()
](
database.md#dropcollection
)
*
[
MongoDB Manual: drop command
](
https://docs.mongodb.org/manual/reference/command/drop/
)
*
[
MongoDB Manual: drop command
](
https://docs.mongodb.org/manual/reference/command/drop/
)
---
---
...
...
docs/classes/database.md
View file @
a2d91319
# MongoDB\Database
# MongoDB\Database
`MongoDB\Database`
provides methods for common operations on a database, such
The MongoDB
\D
atabase class provides methods for common operations on a database,
as creating, enumerating, and dropp
ing collections.
such as executing commands and manag
ing collections.
A Database may be constructed directly (using the extension's Manager class) or
A Database may be constructed directly (using the extension's Manager class) or
selected from the library's Client class. It supports the following options:
selected from the library's
[
Client
](
client.md
)
class. It supports the following
options:
*
[
readConcern
](
http://php.net/mongodb-driver-readconcern
)
*
[
readConcern
](
http://php.net/mongodb-driver-readconcern
)
*
[
readPreference
](
http://php.net/mongodb-driver-readpreference
)
*
[
readPreference
](
http://php.net/mongodb-driver-readpreference
)
...
@@ -14,97 +15,192 @@ selected from the library's Client class. It supports the following options:
...
@@ -14,97 +15,192 @@ selected from the library's Client class. It supports the following options:
If any options are omitted, they will be inherited from the Manager constructor
If any options are omitted, they will be inherited from the Manager constructor
argument or object from which the Database was selected.
argument or object from which the Database was selected.
Operations within the Database class (e.g.
`command()`
) will generally inherit
Operations within the Database class (e.g.
[
command()
](
#command
)
) will generally
the Database's options.
inherit
the Database's options.
### Selecting Collections
---
The Database class provides methods for creating Collection instances (using its
## __construct()
internal Manager instance). When selecting a Collection, the child will inherit
options (e.g. read preference, type map) from the Database. New options may also
be provided to the
`selectCollection()`
method.
```
php
function
__construct
(
MongoDB\Driver\Manager
$manager
,
$databaseName
,
array
$options
=
[])
```
```
$db = (new MongoDB\Client)->demo;
/* Select the "users" collection */
If the Database is constructed explicitly, any omitted options will be inherited
$collection = $db->selectCollection('users');
from the Manager object. If the Database is selected from a
[
Client
](
client.md
)
object, options will be inherited from that object.
/* selectCollection() also takes an options array, which can override any
### Supported Options
* options inherited from the Database. */
$collection = $client->selectCollection('users', [
readConcern (MongoDB
\D
river
\R
eadConcern)
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
: The default read concern to use for database operations and selected
]);
collections. Defaults to the Manager's read concern.
readPreference (MongoDB
\D
river
\R
eadPreference)
: 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
\D
river
\W
riteConcern)
: 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
)
---
/* The property accessor may also be used to select a collection without
## __get()
* specifying additional options. PHP's complex syntax may be used for selecting
* collection whose names contain special characters (e.g. "."). */
```
php
$collection = $db->users;
function
__get
(
$collectionName
)
:
MongoDB\Collection
$collection = $db->{'system.profile'};
```
```
## Database-level Operations
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
)
.
The Database class has methods for database-level operations, such as dropping
### Example
the database, executing a command, or managing the database's collections.
### Dropping the Database
The following example selects the "demo.users" and "demo.system.profile"
collections:
```
```
<?php
$db = (new MongoDB\Client)->demo;
$db = (new MongoDB\Client)->demo;
$
result = $db->drop()
;
$
users = $db->users
;
var_dump($result)
;
$systemProfile = $db->{'system.profile'}
;
```
```
The above example would output something similar to:
### 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
```
```
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
Execute a command on this database.
array(2) {
["dropped"]=>
### Supported Options
string(4) "demo"
["ok"]=>
readPreference (MongoDB
\D
river
\R
eadPreference)
float(1)
: 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
```
```
### Executing a Command
Create a new collection explicitly. Returns the command result document.
While the library provides helpers for some common database commands, it is far
MongoDB already creates collections implicitly when they are first referenced in
from an
[
exhaustive list
](
https://docs.mongodb.org/manual/reference/command/
)
.
commands (e.g. inserting a document into a new collection); however, collections
The following example demonstrates how the
may also be explicitly created with specific options. This is useful for
[
createUser
](
https://docs.mongodb.org/manual/reference/command/createUser/
)
creating
[
capped collections
][
capped
]
, enabling
command might be invoked:
[
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;
$db = (new MongoDB\Client)->demo;
/* Define a command document for creating a new database user */
$result = $db->createCollection('users', [
$createUserCmd = [
'validator' => [
'createUser' => 'username',
'username' => ['$type' => 'string'],
'pwd' => 'password',
'email' => ['$regex' => '@mongodb\.com$'],
'roles' => [ 'readWrite' ],
],
];
/* It doesn't hurt to specify an explicit read preference for the command, in
* case the Database was created with a different read preference. This isn't
* required for other command helpers, as the library knows which commands might
* require a primary; however, the Database::command() method is generic. */
$cursor = $db->command($createUserCmd, [
'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY),
]);
]);
/* The command result will be the first and only document in the cursor */
var_dump($result);
var_dump($cursor->toArray()[0]);
```
```
The above example would output something similar to:
The above example would output something similar to:
```
```
object(MongoDB\Model\BSONDocument)#
8
(1) {
object(MongoDB\Model\BSONDocument)#
11
(1) {
["storage":"ArrayObject":private]=>
["storage":"ArrayObject":private]=>
array(1) {
array(1) {
["ok"]=>
["ok"]=>
...
@@ -113,30 +209,35 @@ object(MongoDB\Model\BSONDocument)#8 (1) {
...
@@ -113,30 +209,35 @@ object(MongoDB\Model\BSONDocument)#8 (1) {
}
}
```
```
##
Collection Management
##
# See Also
The Database class has several methods for managing collections.
*
[
MongoDB Manual: create command
](
http://docs.mongodb.org/manual/reference/command/create/
)
### Creating Collections
---
MongoDB already creates collections implicitly when they are first referenced in
## drop
commands (e.g. inserting a document into a new collection); however, collections
may also be explicitly created with specific options. This is useful for
```
php
creating
function
drop
(
array
$options
=
[])
:
array
|
object
[
capped collections
](
https://docs.mongodb.org/manual/core/capped-collections/
)
,
```
enabling
[
document validation
](
https://docs.mongodb.org/manual/core/document-validation/
)
,
Drop this database. Returns the command result document.
or supplying storage engine options.
### 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;
$db = (new MongoDB\Client)->demo;
$result = $db->createCollection('users', [
$result = $db->drop();
'validator' => [
'username' => ['$type' => 'string'],
'email' => ['$regex' => '@mongodb\.com$'],
],
]);
var_dump($result);
var_dump($result);
```
```
...
@@ -145,19 +246,47 @@ The above example would output something similar to:
...
@@ -145,19 +246,47 @@ The above example would output something similar to:
```
```
object(MongoDB\Model\BSONDocument)#11 (1) {
object(MongoDB\Model\BSONDocument)#11 (1) {
["storage":"ArrayObject":private]=>
["storage":"ArrayObject":private]=>
array(1) {
array(2) {
["dropped"]=>
string(4) "demo"
["ok"]=>
["ok"]=>
float(1)
float(1)
}
}
}
}
```
```
### Dropping Collections
### 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;
$db = (new MongoDB\Client)->demo;
$result = $db->dropCollection('users');
$result = $db->dropCollection('users');
var_dump($result);
var_dump($result);
```
```
...
@@ -177,15 +306,49 @@ object(MongoDB\Model\BSONDocument)#11 (1) {
...
@@ -177,15 +306,49 @@ object(MongoDB\Model\BSONDocument)#11 (1) {
}
}
```
```
### Enumerating Collections
### See Also
*
[
MongoDB\Collection::drop()
](
collection.md#drop
)
*
[
MongoDB Manual: drop command
](
http://docs.mongodb.org/manual/reference/command/drop/
)
The Database class implements MongoDB's
---
[
Enumerating Collections specification
](
https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst
)
.
## 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
\M
odel
\C
ollectionInfo 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;
$db = (new MongoDB\Client)->demo;
/* listCollections() returns an iterator of MongoDB\Model\CollectionInfo objects */
foreach ($db->listCollections() as $collectionInfo) {
foreach ($db->listCollections() as $collectionInfo) {
var_dump($collectionInfo);
var_dump($collectionInfo);
}
}
...
@@ -213,3 +376,103 @@ object(MongoDB\Model\CollectionInfo)#13 (2) {
...
@@ -213,3 +376,103 @@ object(MongoDB\Model\CollectionInfo)#13 (2) {
}
}
}
}
```
```
### 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
\D
river
\R
eadConcern)
: The default read concern to use for collection operations. Defaults to the
Database's read concern.
readPreference (MongoDB
\D
river
\R
eadPreference)
: 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
\D
river
\W
riteConcern)
: 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
\D
river
\R
eadConcern)
: The default read concern to use for database operations and selected
collections. Defaults to the Manager's read concern.
readPreference (MongoDB
\D
river
\R
eadPreference)
: 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
\D
river
\W
riteConcern)
: 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
)
docs/tutorial/commands.md
0 → 100644
View file @
a2d91319
# 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
[
aggregate
][
aggregate
]
with the "cursor" option, may
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:
[
aggregate
]:
http://docs.mongodb.org/manual/reference/command/aggregate/
[
find
]:
../classes/collection.md#find
```
<?php
$database = (new MongoDB\Client)->demo;
$cursor = $database->command([
'aggregate' => 'zips',
'pipeline' => [
['$group' => ['_id' => '$state', 'count' => ['$sum' => 1]]],
['$sort' => ['count' => -1]],
['$limit' => 5],
],
'cursor' => new \stdClass,
]);
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
```
## 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)
}
}
```
mkdocs.yml
View file @
a2d91319
...
@@ -10,6 +10,7 @@ pages:
...
@@ -10,6 +10,7 @@ pages:
-
'
Upgrade
Guide'
:
'
upgrade-guide.md'
-
'
Upgrade
Guide'
:
'
upgrade-guide.md'
-
Tutorial
:
-
Tutorial
:
-
'
CRUD
Operations'
:
'
tutorial/crud.md'
-
'
CRUD
Operations'
:
'
tutorial/crud.md'
-
'
Database
Commands'
:
'
tutorial/commands.md'
-
'
Indexes'
:
'
tutorial/indexes.md'
-
'
Indexes'
:
'
tutorial/indexes.md'
-
'
Example
Data'
:
'
tutorial/example-data.md'
-
'
Example
Data'
:
'
tutorial/example-data.md'
-
Classes
:
-
Classes
:
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment