database.md 11.5 KB
Newer Older
1 2
# MongoDB\Database

3 4
The MongoDB\Database class provides methods for common operations on a database,
such as executing commands and managing collections.
5 6

A Database may be constructed directly (using the extension's Manager class) or
7 8
selected from the library's [Client](client.md) class. It supports the following
options:
9 10 11 12 13 14 15 16 17

 * [readConcern](http://php.net/mongodb-driver-readconcern)
 * [readPreference](http://php.net/mongodb-driver-readpreference)
 * [typeMap](http://php.net/manual/en/mongodb.persistence.php#mongodb.persistence.typemaps)
 * [writeConcern](http://php.net/mongodb-driver-writeconcern)

If any options are omitted, they will be inherited from the Manager constructor
argument or object from which the Database was selected.

18 19
Operations within the Database class (e.g. [command()](#command)) will generally
inherit the Database's options.
20

21
---
22

23
## __construct()
24

25 26
```php
function __construct(MongoDB\Driver\Manager $manager, $databaseName, array $options = [])
27 28
```

29 30 31
If the Database is constructed explicitly, any omitted options will be inherited
from the Manager object. If the Database is selected from a [Client](client.md)
object, options will be inherited from that object.
32

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
### Supported Options

readConcern (MongoDB\Driver\ReadConcern)
:   The default read concern to use for database operations and selected
    collections. Defaults to the Manager's read concern.

readPreference (MongoDB\Driver\ReadPreference)
:   The default read preference to use for database operations and selected
    collections. Defaults to the Manager's read preference.

typeMap (array)
:   Default type map for cursors and BSON documents.

writeConcern (MongoDB\Driver\WriteConcern)
:   The default write concern to use for database operations and selected
    collections. Defaults to the Manager's write concern.

### See Also

 * [MongoDB\Database::withOptions()](#withoptions)

---
55

56 57 58 59
## __get()

```php
function __get($collectionName): MongoDB\Collection
60 61
```

62 63 64 65 66 67 68 69 70
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).
71

72
### Example
73

74 75
The following example selects the "demo.users" and "demo.system.profile"
collections:
76 77

```
78 79
<?php

80 81
$db = (new MongoDB\Client)->demo;

82 83
$users = $db->users;
$systemProfile = $db->{'system.profile'};
84 85
```

86 87 88 89 90 91 92 93
### See Also

 * [MongoDB\Database::selectCollection()](#selectcollection)
 * [PHP Manual: Property Overloading](http://php.net/oop5.overloading#object.get)

---

## command()
94

95 96
```php
function function command($command, array $options = []): MongoDB\Driver\Cursor
97
```
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

Execute a command on this database.

### Supported Options

readPreference (MongoDB\Driver\ReadPreference)
:   The read preference to use when executing the command. This may be used when
    issuing the command to a replica set or mongos node to ensure that the
    driver sets the wire protocol accordingly or adds the read preference to the
    command document, respectively.

typeMap (array)
:   Type map for BSON deserialization. This will be applied to the returned
    Cursor (it is not sent to the server).

### See Also

 * [Tutorial: Database Commands](../tutorial/commands.md)
 * [MongoDB Manual: Database Commands](https://docs.mongodb.org/manual/reference/command/)

## createCollection

```php
function createCollection($collectionName, array $options = []): array|object
122 123
```

124
Create a new collection explicitly. Returns the command result document.
125

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
MongoDB already creates collections implicitly when they are first referenced in
commands (e.g. inserting a document into a new collection); however, collections
may also be explicitly created with specific options. This is useful for
creating [capped collections][capped], enabling
[document validation][validation], or supplying storage engine options.

[capped]: https://docs.mongodb.org/manual/core/capped-collections/
[validation]: https://docs.mongodb.org/manual/core/document-validation/

### Supported Options

autoIndexId (boolean)
:   Specify false to disable the automatic creation of an index on the _id
    field. For replica sets, this option cannot be false. The default is true.

capped (boolean)
:   Specify true to create a capped collection. If set, the size option must
    also be specified. The default is false.

flags (integer)
:   Options for the MMAPv1 storage engine only. Must be a bitwise combination
    `MongoDB\Operation\CreateCollection::USE_POWER_OF_2_SIZES` and
    `MongoDB\Operation\CreateCollection::NO_PADDING`. The default is
    `MongoDB\Operation\CreateCollection::USE_POWER_OF_2_SIZES`.

indexOptionDefaults (document)
:   Default configuration for indexes when creating the collection.

max (integer)
:   The maximum number of documents allowed in the capped collection. The size
    option takes precedence over this limit.

maxTimeMS (integer)
:   The maximum amount of time to allow the query to run.

size (integer)
:   The maximum number of bytes for a capped collection.

storageEngine (document)
:   Storage engine options.

typeMap (array)
:   Type map for BSON deserialization. This will only be used for the returned
    command result document.

validationAction (string)
:   Validation action.

validationLevel (string)
:   Validation level.

validator (document)
:   Validation rules or expressions.

### Example

The following example creates the "demo.users" collection with a custom
[document validator][validation] (available in MongoDB 3.2+):
184 185

```
186 187
<?php

188 189
$db = (new MongoDB\Client)->demo;

190 191 192 193 194
$result = $db->createCollection('users', [
    'validator' => [
        'username' => ['$type' => 'string'],
        'email' => ['$regex' => '@mongodb\.com$'],
    ],
195 196
]);

197
var_dump($result);
198 199 200 201 202
```

The above example would output something similar to:

```
203
object(MongoDB\Model\BSONDocument)#11 (1) {
204 205 206 207 208 209 210 211
  ["storage":"ArrayObject":private]=>
  array(1) {
    ["ok"]=>
    float(1)
  }
}
```

212
### See Also
213

214
 * [MongoDB Manual: create command](http://docs.mongodb.org/manual/reference/command/create/)
215

216
---
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## drop

```php
function drop(array $options = []): array|object
```

Drop this database. Returns the command result document.

### Supported Options

typeMap (array)
:   Type map for BSON deserialization. This will only be used for the returned
    command result document.

### Example

The following example drops the "demo" database:
235 236 237 238

```
$db = (new MongoDB\Client)->demo;

239 240
$result = $db->drop();

241 242 243 244 245 246 247 248
var_dump($result);
```

The above example would output something similar to:

```
object(MongoDB\Model\BSONDocument)#11 (1) {
  ["storage":"ArrayObject":private]=>
249 250 251
  array(2) {
    ["dropped"]=>
    string(4) "demo"
252 253 254 255 256 257
    ["ok"]=>
    float(1)
  }
}
```

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
### 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:
282 283

```
284 285
<?php

286 287 288
$db = (new MongoDB\Client)->demo;

$result = $db->dropCollection('users');
289

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
var_dump($result);
```

The above example would output something similar to:

```
object(MongoDB\Model\BSONDocument)#11 (1) {
  ["storage":"ArrayObject":private]=>
  array(3) {
    ["ns"]=>
    string(10) "demo.users"
    ["nIndexesWas"]=>
    int(1)
    ["ok"]=>
    float(1)
  }
}
```

309 310 311 312
### See Also

 * [MongoDB\Collection::drop()](collection.md#drop)
 * [MongoDB Manual: drop command](http://docs.mongodb.org/manual/reference/command/drop/)
313

314
---
315

316 317 318 319 320 321 322 323 324 325 326 327 328 329
## getDatabaseName()

```php
function getDatabaseName(): string
```

Return the database name.

---

## listCollections()

```php
function listCollections(array $options = []): MongoDB\Model\CollectionInfoIterator
330
```
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

Returns information for all collections in this database. Elements in the
returned iterator will be MongoDB\Model\CollectionInfo objects.

### Supported Options

filter (document)
:   Query by which to filter collections.

maxTimeMS (integer)
:   The maximum amount of time to allow the query to run.

### Example

The following example lists all collections in the "demo" database:

```
<?php

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
$db = (new MongoDB\Client)->demo;

foreach ($db->listCollections() as $collectionInfo) {
    var_dump($collectionInfo);
}
```

The above example would output something similar to:

```
object(MongoDB\Model\CollectionInfo)#8 (2) {
  ["name"]=>
  string(5) "users"
  ["options"]=>
  array(0) {
  }
}
object(MongoDB\Model\CollectionInfo)#13 (2) {
  ["name"]=>
  string(14) "system.profile"
  ["options"]=>
  array(2) {
    ["capped"]=>
    bool(true)
    ["size"]=>
    int(1048576)
  }
}
```
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

### See Also

 * [MongoDB Manual: listCollections command](http://docs.mongodb.org/manual/reference/command/listCollections/)
 * [MongoDB Specification: Enumerating Collections](https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst)

---

## selectCollection()

```php
function selectCollection($collectionName, array $options = []): MongoDB\Collection
```

Select a collection within this database.

The Collection will inherit options (e.g. read preference, type map) from the
Database object unless otherwise specified.

### Supported Options

readConcern (MongoDB\Driver\ReadConcern)
:   The default read concern to use for collection operations. Defaults to the
    Database's read concern.

readPreference (MongoDB\Driver\ReadPreference)
:   The default read preference to use for collection operations. Defaults to
    the Database's read preference.

typeMap (array)
:   Default type map for cursors and BSON documents. Defaults to the Database's
    type map.

writeConcern (MongoDB\Driver\WriteConcern)
:   The default write concern to use for collection operations. Defaults to the
    Database's write concern.

### Example

The following example selects the "demo.users" collection:

```
<?php

$db = (new MongoDB\Client)->demo;

$collection = $db->selectCollection('users');
```

The following examples selects the "demo.users" collection with a custom read
preference:

```
<?php

$db = (new MongoDB\Client)->demo;

$collection = $db->selectCollection(
    'users',
    [
        'readPreference' => new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY),
    ]
);
```

### See Also

 * [MongoDB\Collection::__construct()](collection.md#__construct)
 * [MongoDB\Database::__get()](#__get)

---

## withOptions()

```php
function withOptions(array $options = []): MongoDB\Database
```

Returns a clone of this database with different options.

### Supported Options

readConcern (MongoDB\Driver\ReadConcern)
:   The default read concern to use for database operations and selected
    collections. Defaults to the Manager's read concern.

readPreference (MongoDB\Driver\ReadPreference)
:   The default read preference to use for database operations and selected
    collections. Defaults to the Manager's read preference.

typeMap (array)
:   Default type map for cursors and BSON documents.

writeConcern (MongoDB\Driver\WriteConcern)
:   The default write concern to use for database operations and selected
    collections. Defaults to the Manager's write concern.

### See Also

 * [MongoDB\Database::__construct()](#__construct)