collection.md 26.6 KB
Newer Older
1 2
# MongoDB\Collection

3 4 5
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.
6

7 8 9 10
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:
11 12 13 14 15 16

 * [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)

17 18 19 20 21 22 23
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.
24

25
[findandmodify]: http://docs.mongodb.org/manual/reference/command/findAndModify/
26

27
---
28

29
## __construct()
30

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
```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)
60
 * [MongoDB\Database::selectCollection()](database.md#selectcollection)
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

---

## 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
78 79 80 81 82 83
command cursor) does not yet support a "typeMap" options; however, classes
implementing [MongoDB\BSON\Persistable][persistable] will still be deserialized
according to the [Persistence][persistence] specification.

[persistable]: http://php.net/mongodb-bson-persistable
[persistence]: http://php.net/manual/en/mongodb.persistence.deserialization.php
84 85 86 87 88 89 90 91 92 93 94 95 96 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 122 123 124 125 126 127 128 129 130 131 132 133

### 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/)
134
 * [MongoDB Manual: Aggregation Pipeline](https://docs.mongodb.org/manual/core/aggregation-pipeline/)
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

---

## 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.
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
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[]
270
```
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

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

395 396 397
$collection = (new MongoDB\Client)->demo->zips;

$result = $collection->drop();
398

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
var_dump($result);
```

The above example would output something similar to:

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

418 419
### See Also

420
 * [MongoDB\Database::dropCollection()](database.md#dropcollection)
421
 * [MongoDB Manual: drop command](https://docs.mongodb.org/manual/reference/command/drop/)
422

423
---
424

425 426 427 428 429
## dropIndex()

```php
function dropIndex($indexName, array $options = []): array|object
```
430

431
Drop a single index in the collection. Returns the command result document.
432

433
### Supported Options
434

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

439
### See Also
440

441 442 443 444
 * [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]
445

446
---
447

448 449 450 451
## dropIndexes()

```php
function dropIndexes(array $options = []): array|object
452 453
```

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
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
475 476
```

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
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.
521

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
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
547
```
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596

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
597 598
```

599 600 601 602
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
603 604 605
"typeMap" option; however, classes implementing
[MongoDB\BSON\Persistable][persistable] will still be deserialized according to
the [Persistence][persistence] specification.
606 607

### Supported Options
608

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

612 613
projection (document)
:   Limits the fields to return for the matching document.
614

615 616 617
sort (document)
:   Determines which document the operation modifies if the query selects
    multiple documents.
618

619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
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
634 635
```

636 637 638 639 640 641 642 643 644
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
645 646 647
"typeMap" option; however, classes implementing
[MongoDB\BSON\Persistable][persistable] will still be deserialized according to
the [Persistence][persistence] specification.
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

### 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
689 690
```

691 692 693 694 695 696 697 698 699
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
700 701 702
"typeMap" option; however, classes implementing
[MongoDB\BSON\Persistable][persistable] will still be deserialized according to
the [Persistence][persistence] specification.
703 704 705 706 707 708 709 710

### 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.
711

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
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
744
```
745 746 747 748 749 750 751 752 753

Return the collection name.

---

## getDatabaseName()

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

756 757 758 759 760
Return the database name.

---

## getNamespace()
761

762 763
```php
function getNamespace(): string
764 765
```

766 767 768 769 770 771 772 773 774 775 776 777
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
778 779
```

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
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/)
801

802 803 804 805 806 807
---

## insertOne()

```php
function insertOne($document, array $options = []): MongoDB\InsertOneResult
808
```
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

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
833 834
```

835 836 837 838
Returns information for all indexes for the collection. Elements in the returned
iterator will be MongoDB\Model\IndexInfo objects.

### Supported Options
839

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
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
856 857
```

858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
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
886 887
```

888 889 890 891 892 893
Updates all documents matching the filter.

### Supported Options

bypassDocumentValidation (boolean)
:   If true, allows the write to opt out of document level validation.
894

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
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
916
```
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945

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
946
```
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969

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)