Collection.php 34.6 KB
Newer Older
1
<?php
2

3 4
namespace MongoDB;

5
use MongoDB\Driver\Cursor;
6
use MongoDB\Driver\Manager;
7
use MongoDB\Driver\ReadConcern;
8 9
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;
10
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
11
use MongoDB\Exception\InvalidArgumentException;
12 13
use MongoDB\Exception\UnexpectedValueException;
use MongoDB\Exception\UnsupportedException;
14
use MongoDB\Model\IndexInfoIterator;
15
use MongoDB\Operation\Aggregate;
16
use MongoDB\Operation\BulkWrite;
17
use MongoDB\Operation\CreateIndexes;
18
use MongoDB\Operation\Count;
19 20
use MongoDB\Operation\DeleteMany;
use MongoDB\Operation\DeleteOne;
21
use MongoDB\Operation\Distinct;
22
use MongoDB\Operation\DropCollection;
23
use MongoDB\Operation\DropIndexes;
24 25
use MongoDB\Operation\Find;
use MongoDB\Operation\FindOne;
26 27 28
use MongoDB\Operation\FindOneAndDelete;
use MongoDB\Operation\FindOneAndReplace;
use MongoDB\Operation\FindOneAndUpdate;
29 30
use MongoDB\Operation\InsertMany;
use MongoDB\Operation\InsertOne;
31
use MongoDB\Operation\ListIndexes;
32 33 34
use MongoDB\Operation\ReplaceOne;
use MongoDB\Operation\UpdateMany;
use MongoDB\Operation\UpdateOne;
35
use Traversable;
36

37 38
class Collection
{
39 40 41 42 43
    private static $defaultTypeMap = [
        'array' => 'MongoDB\Model\BSONArray',
        'document' => 'MongoDB\Model\BSONDocument',
        'root' => 'MongoDB\Model\BSONDocument',
    ];
44
    private static $wireVersionForFindAndModifyWriteConcern = 4;
45
    private static $wireVersionForReadConcern = 4;
46
    private static $wireVersionForWritableCommandWriteConcern = 5;
47

48 49 50
    private $collectionName;
    private $databaseName;
    private $manager;
51
    private $readConcern;
52
    private $readPreference;
53
    private $typeMap;
54
    private $writeConcern;
Hannes Magnusson's avatar
Hannes Magnusson committed
55

56
    /**
57
     * Constructs new Collection instance.
58
     *
59 60
     * This class provides methods for collection-specific operations, such as
     * CRUD (i.e. create, read, update, and delete) and index management.
61
     *
62 63
     * Supported options:
     *
64 65 66
     *  * readConcern (MongoDB\Driver\ReadConcern): The default read concern to
     *    use for collection operations. Defaults to the Manager's read concern.
     *
67 68 69 70
     *  * readPreference (MongoDB\Driver\ReadPreference): The default read
     *    preference to use for collection operations. Defaults to the Manager's
     *    read preference.
     *
71 72
     *  * typeMap (array): Default type map for cursors and BSON documents.
     *
73 74 75 76
     *  * writeConcern (MongoDB\Driver\WriteConcern): The default write concern
     *    to use for collection operations. Defaults to the Manager's write
     *    concern.
     *
77 78 79 80
     * @param Manager $manager        Manager instance from the driver
     * @param string  $databaseName   Database name
     * @param string  $collectionName Collection name
     * @param array   $options        Collection options
81
     * @throws InvalidArgumentException for parameter/option parsing errors
82
     */
83
    public function __construct(Manager $manager, $databaseName, $collectionName, array $options = [])
84
    {
85 86
        if (strlen($databaseName) < 1) {
            throw new InvalidArgumentException('$databaseName is invalid: ' . $databaseName);
87 88
        }

89 90 91
        if (strlen($collectionName) < 1) {
            throw new InvalidArgumentException('$collectionName is invalid: ' . $collectionName);
        }
92

93
        if (isset($options['readConcern']) && ! $options['readConcern'] instanceof ReadConcern) {
94
            throw InvalidArgumentException::invalidType('"readConcern" option', $options['readConcern'], 'MongoDB\Driver\ReadConcern');
95 96
        }

97
        if (isset($options['readPreference']) && ! $options['readPreference'] instanceof ReadPreference) {
98
            throw InvalidArgumentException::invalidType('"readPreference" option', $options['readPreference'], 'MongoDB\Driver\ReadPreference');
99 100
        }

101
        if (isset($options['typeMap']) && ! is_array($options['typeMap'])) {
102
            throw InvalidArgumentException::invalidType('"typeMap" option', $options['typeMap'], 'array');
103 104
        }

105
        if (isset($options['writeConcern']) && ! $options['writeConcern'] instanceof WriteConcern) {
106
            throw InvalidArgumentException::invalidType('"writeConcern" option', $options['writeConcern'], 'MongoDB\Driver\WriteConcern');
107 108
        }

109
        $this->manager = $manager;
110 111
        $this->databaseName = (string) $databaseName;
        $this->collectionName = (string) $collectionName;
112
        $this->readConcern = isset($options['readConcern']) ? $options['readConcern'] : $this->manager->getReadConcern();
113
        $this->readPreference = isset($options['readPreference']) ? $options['readPreference'] : $this->manager->getReadPreference();
114
        $this->typeMap = isset($options['typeMap']) ? $options['typeMap'] : self::$defaultTypeMap;
115
        $this->writeConcern = isset($options['writeConcern']) ? $options['writeConcern'] : $this->manager->getWriteConcern();
116
    }
117

118 119 120 121
    /**
     * Return internal properties for debugging purposes.
     *
     * @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
122
     * @return array
123 124 125 126 127 128 129
     */
    public function __debugInfo()
    {
        return [
            'collectionName' => $this->collectionName,
            'databaseName' => $this->databaseName,
            'manager' => $this->manager,
130
            'readConcern' => $this->readConcern,
131
            'readPreference' => $this->readPreference,
132
            'typeMap' => $this->typeMap,
133 134 135 136
            'writeConcern' => $this->writeConcern,
        ];
    }

137
    /**
138
     * Return the collection namespace (e.g. "db.collection").
139
     *
140
     * @see https://docs.mongodb.org/manual/faq/developers/#faq-dev-namespace
141
     * @return string
142 143 144
     */
    public function __toString()
    {
145
        return $this->databaseName . '.' . $this->collectionName;
146 147
    }

148
    /**
149
     * Executes an aggregation framework pipeline on the collection.
150 151 152 153 154
     *
     * Note: this method's return value depends on the MongoDB server version
     * and the "useCursor" option. If "useCursor" is true, a Cursor will be
     * returned; otherwise, an ArrayIterator is returned, which wraps the
     * "result" array from the command response document.
155
     *
156 157 158 159
     * @see Aggregate::__construct() for supported options
     * @param array $pipeline List of pipeline operations
     * @param array $options  Command options
     * @return Traversable
160 161 162 163
     * @throws UnexpectedValueException if the command response was malformed
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
164
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
165
    public function aggregate(array $pipeline, array $options = [])
166
    {
167 168
        $hasOutStage = \MongoDB\is_last_pipeline_operator_out($pipeline);

169 170 171 172
        if ( ! isset($options['readPreference'])) {
            $options['readPreference'] = $this->readPreference;
        }

173
        if ($hasOutStage) {
174 175 176
            $options['readPreference'] = new ReadPreference(ReadPreference::RP_PRIMARY);
        }

177 178 179 180 181 182 183 184 185 186 187
        $server = $this->manager->selectServer($options['readPreference']);

        /* A "majority" read concern is not compatible with the $out stage, so
         * avoid providing the Collection's read concern if it would conflict.
         */
        if ( ! isset($options['readConcern']) &&
             ! ($hasOutStage && $this->readConcern->getLevel() === ReadConcern::MAJORITY) &&
            \MongoDB\server_supports_feature($server, self::$wireVersionForReadConcern)) {
            $options['readConcern'] = $this->readConcern;
        }

188
        if ( ! isset($options['typeMap']) && ( ! isset($options['useCursor']) || $options['useCursor'])) {
189 190 191
            $options['typeMap'] = $this->typeMap;
        }

192 193 194 195 196 197
        if ($hasOutStage && ! isset($options['writeConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern)) {
            $options['writeConcern'] = $this->writeConcern;
        }

        $operation = new Aggregate($this->databaseName, $this->collectionName, $pipeline, $options);

198
        return $operation->execute($server);
199 200 201
    }

    /**
202
     * Executes multiple write operations.
203
     *
204 205 206 207
     * @see BulkWrite::__construct() for supported options
     * @param array[] $operations List of write operations
     * @param array   $options    Command options
     * @return BulkWriteResult
208 209 210
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
211
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
212
    public function bulkWrite(array $operations, array $options = [])
213
    {
214
        if ( ! isset($options['writeConcern'])) {
215
            $options['writeConcern'] = $this->writeConcern;
216
        }
217

218
        $operation = new BulkWrite($this->databaseName, $this->collectionName, $operations, $options);
219
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
220

221
        return $operation->execute($server);
222 223 224
    }

    /**
225
     * Gets the number of documents matching the filter.
226
     *
227
     * @see Count::__construct() for supported options
228 229
     * @param array|object $filter  Query by which to filter documents
     * @param array        $options Command options
230
     * @return integer
231 232 233 234
     * @throws UnexpectedValueException if the command response was malformed
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
235
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
236
    public function count($filter = [], array $options = [])
237
    {
238 239 240 241 242
        if ( ! isset($options['readPreference'])) {
            $options['readPreference'] = $this->readPreference;
        }

        $server = $this->manager->selectServer($options['readPreference']);
243

244 245 246 247 248 249
        if ( ! isset($options['readConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForReadConcern)) {
            $options['readConcern'] = $this->readConcern;
        }

        $operation = new Count($this->databaseName, $this->collectionName, $filter, $options);

250
        return $operation->execute($server);
251 252
    }

253
    /**
254
     * Create a single index for the collection.
255
     *
256
     * @see Collection::createIndexes()
257
     * @see CreateIndexes::__construct() for supported command options
258 259 260
     * @param array|object $key     Document containing fields mapped to values,
     *                              which denote order or an index type
     * @param array        $options Index options
261
     * @return string The name of the created index
262 263 264
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
265
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
266
    public function createIndex($key, array $options = [])
267
    {
268 269 270 271
        $indexOptions = array_diff_key($options, ['writeConcern' => 1]);
        $commandOptions = array_intersect_key($options, ['writeConcern' => 1]);

        return current($this->createIndexes([['key' => $key] + $indexOptions], $commandOptions));
272 273 274
    }

    /**
275
     * Create one or more indexes for the collection.
276
     *
277 278 279 280 281 282 283 284 285 286 287 288 289
     * 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:
     *
     *     $indexes = [
     *         // 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.
290 291 292
     *
     * @see http://docs.mongodb.org/manual/reference/command/createIndexes/
     * @see http://docs.mongodb.org/manual/reference/method/db.collection.createIndex/
293
     * @see CreateIndexes::__construct() for supported command options
294
     * @param array[] $indexes List of index specifications
295
     * @param array   $options Command options
296
     * @return string[] The names of the created indexes
297 298 299
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
300
     */
301
    public function createIndexes(array $indexes, array $options = [])
302
    {
303
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
304

305 306 307 308 309 310
        if ( ! isset($options['writeConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern)) {
            $options['writeConcern'] = $this->writeConcern;
        }

        $operation = new CreateIndexes($this->databaseName, $this->collectionName, $indexes, $options);

311
        return $operation->execute($server);
312 313
    }

314
    /**
315
     * Deletes all documents matching the filter.
316
     *
317
     * @see DeleteMany::__construct() for supported options
318
     * @see http://docs.mongodb.org/manual/reference/command/delete/
319 320
     * @param array|object $filter  Query by which to delete documents
     * @param array        $options Command options
321
     * @return DeleteResult
322 323 324
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
325
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
326
    public function deleteMany($filter, array $options = [])
327
    {
328
        if ( ! isset($options['writeConcern'])) {
329
            $options['writeConcern'] = $this->writeConcern;
330 331
        }

332
        $operation = new DeleteMany($this->databaseName, $this->collectionName, $filter, $options);
333
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
334

335
        return $operation->execute($server);
336 337 338
    }

    /**
339
     * Deletes at most one document matching the filter.
340
     *
341
     * @see DeleteOne::__construct() for supported options
342
     * @see http://docs.mongodb.org/manual/reference/command/delete/
343 344
     * @param array|object $filter  Query by which to delete documents
     * @param array        $options Command options
345
     * @return DeleteResult
346 347 348
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
349
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
350
    public function deleteOne($filter, array $options = [])
351
    {
352
        if ( ! isset($options['writeConcern'])) {
353
            $options['writeConcern'] = $this->writeConcern;
354
        }
355

356
        $operation = new DeleteOne($this->databaseName, $this->collectionName, $filter, $options);
357 358 359
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

        return $operation->execute($server);
360 361 362
    }

    /**
363
     * Finds the distinct values for a specified field across the collection.
364
     *
365 366
     * @see Distinct::__construct() for supported options
     * @param string $fieldName Field for which to return distinct values
367 368
     * @param array|object $filter  Query by which to filter documents
     * @param array        $options Command options
369
     * @return mixed[]
370 371 372 373
     * @throws UnexpectedValueException if the command response was malformed
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
374
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
375
    public function distinct($fieldName, $filter = [], array $options = [])
376
    {
377 378 379 380 381
        if ( ! isset($options['readPreference'])) {
            $options['readPreference'] = $this->readPreference;
        }

        $server = $this->manager->selectServer($options['readPreference']);
382

383 384 385 386 387 388
        if ( ! isset($options['readConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForReadConcern)) {
            $options['readConcern'] = $this->readConcern;
        }

        $operation = new Distinct($this->databaseName, $this->collectionName, $fieldName, $filter, $options);

389
        return $operation->execute($server);
390 391
    }

392 393 394
    /**
     * Drop this collection.
     *
395 396 397
     * @see DropCollection::__construct() for supported options
     * @param array $options Additional options
     * @return array|object Command result document
398 399 400
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
401
     */
402
    public function drop(array $options = [])
403
    {
404 405 406 407
        if ( ! isset($options['typeMap'])) {
            $options['typeMap'] = $this->typeMap;
        }

408
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
409

410 411 412 413 414 415
        if ( ! isset($options['writeConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern)) {
            $options['writeConcern'] = $this->writeConcern;
        }

        $operation = new DropCollection($this->databaseName, $this->collectionName, $options);

416
        return $operation->execute($server);
417 418
    }

419 420 421
    /**
     * Drop a single index in the collection.
     *
422
     * @see DropIndexes::__construct() for supported options
423
     * @param string $indexName Index name
424 425
     * @param array  $options   Additional options
     * @return array|object Command result document
426 427 428
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
429
     */
430
    public function dropIndex($indexName, array $options = [])
431
    {
432 433 434 435 436 437
        $indexName = (string) $indexName;

        if ($indexName === '*') {
            throw new InvalidArgumentException('dropIndexes() must be used to drop multiple indexes');
        }

438 439 440 441
        if ( ! isset($options['typeMap'])) {
            $options['typeMap'] = $this->typeMap;
        }

442
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
443

444 445 446 447 448 449
        if ( ! isset($options['writeConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern)) {
            $options['writeConcern'] = $this->writeConcern;
        }

        $operation = new DropIndexes($this->databaseName, $this->collectionName, $indexName, $options);

450
        return $operation->execute($server);
451 452 453 454 455
    }

    /**
     * Drop all indexes in the collection.
     *
456 457 458
     * @see DropIndexes::__construct() for supported options
     * @param array $options Additional options
     * @return array|object Command result document
459 460 461
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
462
     */
463
    public function dropIndexes(array $options = [])
464
    {
465 466 467 468
        if ( ! isset($options['typeMap'])) {
            $options['typeMap'] = $this->typeMap;
        }

469
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
470

471 472 473 474 475 476
        if ( ! isset($options['writeConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForWritableCommandWriteConcern)) {
            $options['writeConcern'] = $this->writeConcern;
        }

        $operation = new DropIndexes($this->databaseName, $this->collectionName, '*', $options);

477
        return $operation->execute($server);
478 479
    }

480
    /**
481
     * Finds documents matching the query.
482
     *
483
     * @see Find::__construct() for supported options
484
     * @see http://docs.mongodb.org/manual/core/read-operations-introduction/
485 486
     * @param array|object $filter  Query by which to filter documents
     * @param array        $options Additional options
487
     * @return Cursor
488 489 490
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
491
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
492
    public function find($filter = [], array $options = [])
493
    {
494 495 496 497
        if ( ! isset($options['readPreference'])) {
            $options['readPreference'] = $this->readPreference;
        }

498 499 500 501 502 503
        $server = $this->manager->selectServer($options['readPreference']);

        if ( ! isset($options['readConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForReadConcern)) {
            $options['readConcern'] = $this->readConcern;
        }

504 505 506 507
        if ( ! isset($options['typeMap'])) {
            $options['typeMap'] = $this->typeMap;
        }

508
        $operation = new Find($this->databaseName, $this->collectionName, $filter, $options);
509

510
        return $operation->execute($server);
511 512
    }

513
    /**
514
     * Finds a single document matching the query.
515
     *
516
     * @see FindOne::__construct() for supported options
517
     * @see http://docs.mongodb.org/manual/core/read-operations-introduction/
518 519
     * @param array|object $filter  Query by which to filter documents
     * @param array        $options Additional options
520
     * @return array|object|null
521 522 523
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
524
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
525
    public function findOne($filter = [], array $options = [])
526
    {
527 528 529 530
        if ( ! isset($options['readPreference'])) {
            $options['readPreference'] = $this->readPreference;
        }

531 532 533 534 535 536
        $server = $this->manager->selectServer($options['readPreference']);

        if ( ! isset($options['readConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForReadConcern)) {
            $options['readConcern'] = $this->readConcern;
        }

537 538 539 540
        if ( ! isset($options['typeMap'])) {
            $options['typeMap'] = $this->typeMap;
        }

541
        $operation = new FindOne($this->databaseName, $this->collectionName, $filter, $options);
542
        $server = $this->manager->selectServer($options['readPreference']);
543

544
        return $operation->execute($server);
545 546
    }

547
    /**
548
     * Finds a single document and deletes it, returning the original.
549
     *
550
     * The document to return may be null if no document matched the filter.
551
     *
552
     * @see FindOneAndDelete::__construct() for supported options
553
     * @see http://docs.mongodb.org/manual/reference/command/findAndModify/
554 555
     * @param array|object $filter  Query by which to filter documents
     * @param array        $options Command options
556
     * @return array|object|null
557 558 559 560
     * @throws UnexpectedValueException if the command response was malformed
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
561
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
562
    public function findOneAndDelete($filter, array $options = [])
563
    {
564
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
565

566 567 568 569
        if ( ! isset($options['writeConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForFindAndModifyWriteConcern)) {
            $options['writeConcern'] = $this->writeConcern;
        }

570 571 572 573
        if ( ! isset($options['typeMap'])) {
            $options['typeMap'] = $this->typeMap;
        }

574 575
        $operation = new FindOneAndDelete($this->databaseName, $this->collectionName, $filter, $options);

576
        return $operation->execute($server);
577 578 579
    }

    /**
580 581
     * Finds a single document and replaces it, returning either the original or
     * the replaced document.
582
     *
583 584 585 586
     * The document to return may be null if no document matched the filter. By
     * default, the original document is returned. Specify
     * FindOneAndReplace::RETURN_DOCUMENT_AFTER for the "returnDocument" option
     * to return the updated document.
587
     *
588
     * @see FindOneAndReplace::__construct() for supported options
589
     * @see http://docs.mongodb.org/manual/reference/command/findAndModify/
590 591 592
     * @param array|object $filter      Query by which to filter documents
     * @param array|object $replacement Replacement document
     * @param array        $options     Command options
593
     * @return array|object|null
594 595 596 597
     * @throws UnexpectedValueException if the command response was malformed
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
598
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
599
    public function findOneAndReplace($filter, $replacement, array $options = [])
600
    {
601
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
602

603 604 605 606
        if ( ! isset($options['writeConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForFindAndModifyWriteConcern)) {
            $options['writeConcern'] = $this->writeConcern;
        }

607 608 609 610
        if ( ! isset($options['typeMap'])) {
            $options['typeMap'] = $this->typeMap;
        }

611 612
        $operation = new FindOneAndReplace($this->databaseName, $this->collectionName, $filter, $replacement, $options);

613
        return $operation->execute($server);
614
    }
615

616
    /**
617 618
     * Finds a single document and updates it, returning either the original or
     * the updated document.
619
     *
620 621 622 623
     * The document to return may be null if no document matched the filter. By
     * default, the original document is returned. Specify
     * FindOneAndUpdate::RETURN_DOCUMENT_AFTER for the "returnDocument" option
     * to return the updated document.
624
     *
625
     * @see FindOneAndReplace::__construct() for supported options
626
     * @see http://docs.mongodb.org/manual/reference/command/findAndModify/
627 628 629
     * @param array|object $filter  Query by which to filter documents
     * @param array|object $update  Update to apply to the matched document
     * @param array        $options Command options
630
     * @return array|object|null
631 632 633 634
     * @throws UnexpectedValueException if the command response was malformed
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
635
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
636
    public function findOneAndUpdate($filter, $update, array $options = [])
637
    {
638
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
639

640 641 642 643
        if ( ! isset($options['writeConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForFindAndModifyWriteConcern)) {
            $options['writeConcern'] = $this->writeConcern;
        }

644 645 646 647
        if ( ! isset($options['typeMap'])) {
            $options['typeMap'] = $this->typeMap;
        }

648 649
        $operation = new FindOneAndUpdate($this->databaseName, $this->collectionName, $filter, $update, $options);

650
        return $operation->execute($server);
651
    }
652

653
    /**
654
     * Return the collection name.
655
     *
656
     * @return string
657
     */
658
    public function getCollectionName()
659
    {
660
        return $this->collectionName;
661 662 663
    }

    /**
664
     * Return the database name.
665 666
     *
     * @return string
667
     */
668
    public function getDatabaseName()
669
    {
670
        return $this->databaseName;
671 672
    }

673 674 675 676 677 678 679 680 681 682
    /**
     * Return the Manager.
     *
     * @return Manager
     */
    public function getManager()
    {
        return $this->manager;
    }

683 684 685
    /**
     * Return the collection namespace.
     *
686
     * @see https://docs.mongodb.org/manual/reference/glossary/#term-namespace
687 688 689 690
     * @return string
     */
    public function getNamespace()
    {
691
        return $this->databaseName . '.' . $this->collectionName;
692 693
    }

694
    /**
695
     * Inserts multiple documents.
696
     *
697
     * @see InsertMany::__construct() for supported options
698
     * @see http://docs.mongodb.org/manual/reference/command/insert/
699
     * @param array[]|object[] $documents The documents to insert
700
     * @param array            $options   Command options
701
     * @return InsertManyResult
702 703
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
704
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
705
    public function insertMany(array $documents, array $options = [])
706
    {
707
        if ( ! isset($options['writeConcern'])) {
708
            $options['writeConcern'] = $this->writeConcern;
709 710
        }

711
        $operation = new InsertMany($this->databaseName, $this->collectionName, $documents, $options);
712
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
713

714
        return $operation->execute($server);
715 716 717
    }

    /**
718
     * Inserts one document.
719
     *
720
     * @see InsertOne::__construct() for supported options
721
     * @see http://docs.mongodb.org/manual/reference/command/insert/
722
     * @param array|object $document The document to insert
723
     * @param array        $options  Command options
724
     * @return InsertOneResult
725 726
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
727
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
728
    public function insertOne($document, array $options = [])
729
    {
730
        if ( ! isset($options['writeConcern'])) {
731
            $options['writeConcern'] = $this->writeConcern;
732 733
        }

734
        $operation = new InsertOne($this->databaseName, $this->collectionName, $document, $options);
735 736 737
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

        return $operation->execute($server);
738
    }
739

740
    /**
741
     * Returns information for all indexes for the collection.
742
     *
743
     * @see ListIndexes::__construct() for supported options
744
     * @return IndexInfoIterator
745 746
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
747
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
748
    public function listIndexes(array $options = [])
749
    {
750
        $operation = new ListIndexes($this->databaseName, $this->collectionName, $options);
751
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
752

753
        return $operation->execute($server);
754 755
    }

756
    /**
757
     * Replaces at most one document matching the filter.
758
     *
759
     * @see ReplaceOne::__construct() for supported options
760
     * @see http://docs.mongodb.org/manual/reference/command/update/
761 762 763
     * @param array|object $filter      Query by which to filter documents
     * @param array|object $replacement Replacement document
     * @param array        $options     Command options
764
     * @return UpdateResult
765 766 767
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
768
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
769
    public function replaceOne($filter, $replacement, array $options = [])
770
    {
771
        if ( ! isset($options['writeConcern'])) {
772
            $options['writeConcern'] = $this->writeConcern;
773 774
        }

775
        $operation = new ReplaceOne($this->databaseName, $this->collectionName, $filter, $replacement, $options);
776 777 778
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

        return $operation->execute($server);
779 780 781
    }

    /**
782
     * Updates all documents matching the filter.
783
     *
784
     * @see UpdateMany::__construct() for supported options
785
     * @see http://docs.mongodb.org/manual/reference/command/update/
786 787 788
     * @param array|object $filter  Query by which to filter documents
     * @param array|object $update  Update to apply to the matched documents
     * @param array        $options Command options
789
     * @return UpdateResult
790 791 792
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
793
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
794
    public function updateMany($filter, $update, array $options = [])
795
    {
796
        if ( ! isset($options['writeConcern'])) {
797
            $options['writeConcern'] = $this->writeConcern;
798
        }
799

800
        $operation = new UpdateMany($this->databaseName, $this->collectionName, $filter, $update, $options);
801 802 803
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

        return $operation->execute($server);
804
    }
805

806
    /**
807
     * Updates at most one document matching the filter.
808
     *
809
     * @see UpdateOne::__construct() for supported options
810
     * @see http://docs.mongodb.org/manual/reference/command/update/
811 812 813
     * @param array|object $filter  Query by which to filter documents
     * @param array|object $update  Update to apply to the matched document
     * @param array        $options Command options
814
     * @return UpdateResult
815 816 817
     * @throws UnsupportedException if options are not supported by the selected server
     * @throws InvalidArgumentException for parameter/option parsing errors
     * @throws DriverRuntimeException for other driver errors (e.g. connection errors)
818
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
819
    public function updateOne($filter, $update, array $options = [])
820
    {
821
        if ( ! isset($options['writeConcern'])) {
822
            $options['writeConcern'] = $this->writeConcern;
823 824
        }

825
        $operation = new UpdateOne($this->databaseName, $this->collectionName, $filter, $update, $options);
826
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));
827

828
        return $operation->execute($server);
829
    }
830 831 832 833

    /**
     * Get a clone of this collection with different options.
     *
834
     * @see Collection::__construct() for supported options
835 836
     * @param array $options Collection constructor options
     * @return Collection
837
     * @throws InvalidArgumentException for parameter/option parsing errors
838 839 840
     */
    public function withOptions(array $options = [])
    {
841 842 843
        $options += [
            'readConcern' => $this->readConcern,
            'readPreference' => $this->readPreference,
844
            'typeMap' => $this->typeMap,
845 846
            'writeConcern' => $this->writeConcern,
        ];
847

848
        return new Collection($this->manager, $this->databaseName, $this->collectionName, $options);
849
    }
850
}